blob: 0a5490d332936513856f357c2316a03b8b9458ea [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,
Emilian Peevab808242020-12-28 16:03:32 -0800378 jint maxImages, jint userFormat, jint userWidth, jint userHeight) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800379 status_t res;
380
381 ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
382
383 sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
384 if (surface == NULL) {
385 jniThrowException(env,
386 "java/lang/IllegalArgumentException",
387 "The surface has been released");
388 return 0;
389 }
390 sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
391
392 jclass clazz = env->GetObjectClass(thiz);
393 if (clazz == NULL) {
394 jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
395 return 0;
396 }
397 sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
398
399 sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
400 ctx->setProducer(producer);
401 /**
402 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
403 * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
404 * will be cleared after disconnect call.
405 */
Emilian Peev2adf4032018-06-05 17:52:16 +0100406 res = producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
407 if (res != OK) {
408 ALOGE("%s: Connecting to surface producer interface failed: %s (%d)",
409 __FUNCTION__, strerror(-res), res);
410 jniThrowRuntimeException(env, "Failed to connect to native window");
411 return 0;
412 }
413
Zhijun Hef6a09e52015-02-24 18:12:23 -0800414 jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
415
416 // Get the dimension and format of the producer.
417 sp<ANativeWindow> anw = producer;
Zhijun He916d8ac2017-03-22 17:33:47 -0700418 int32_t width, height, surfaceFormat;
Emilian Peevab808242020-12-28 16:03:32 -0800419 if (userWidth < 0) {
420 if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
421 ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
422 jniThrowRuntimeException(env, "Failed to query Surface width");
423 return 0;
424 }
425 } else {
426 width = userWidth;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800427 }
Emilian Peevab808242020-12-28 16:03:32 -0800428
Zhijun Hef6a09e52015-02-24 18:12:23 -0800429 ctx->setBufferWidth(width);
430
Emilian Peevab808242020-12-28 16:03:32 -0800431 if (userHeight < 0) {
432 if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
433 ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
434 jniThrowRuntimeException(env, "Failed to query Surface height");
435 return 0;
436 }
437 } else {
438 height = userHeight;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800439 }
440 ctx->setBufferHeight(height);
441
Emilian Peevab808242020-12-28 16:03:32 -0800442 if ((userWidth > 0) && (userHeight > 0)) {
443 res = native_window_set_buffers_user_dimensions(anw.get(), userWidth, userHeight);
444 if (res != OK) {
445 ALOGE("%s: Set buffer dimensions failed: %s (%d)", __FUNCTION__, strerror(-res), res);
446 jniThrowRuntimeException(env, "Set buffer dimensions failed");
447 return 0;
448 }
449 }
450
Zhijun He916d8ac2017-03-22 17:33:47 -0700451 // Query surface format if no valid user format is specified, otherwise, override surface format
452 // with user format.
453 if (userFormat == IMAGE_FORMAT_UNKNOWN) {
454 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceFormat)) != OK) {
455 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
456 jniThrowRuntimeException(env, "Failed to query Surface format");
457 return 0;
458 }
459 } else {
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700460 // Set consumer buffer format to user specified format
461 PublicFormat publicFormat = static_cast<PublicFormat>(userFormat);
462 int nativeFormat = mapPublicFormatToHalFormat(publicFormat);
463 android_dataspace nativeDataspace = mapPublicFormatToHalDataspace(publicFormat);
464 res = native_window_set_buffers_format(anw.get(), nativeFormat);
465 if (res != OK) {
466 ALOGE("%s: Unable to configure consumer native buffer format to %#x",
467 __FUNCTION__, nativeFormat);
468 jniThrowRuntimeException(env, "Failed to set Surface format");
469 return 0;
470 }
471
472 res = native_window_set_buffers_data_space(anw.get(), nativeDataspace);
473 if (res != OK) {
474 ALOGE("%s: Unable to configure consumer dataspace %#x",
475 __FUNCTION__, nativeDataspace);
476 jniThrowRuntimeException(env, "Failed to set Surface dataspace");
477 return 0;
478 }
Sally Qiac97f992021-10-11 17:39:54 -0700479 ctx->setBufferDataSpace(nativeDataspace);
Zhijun He916d8ac2017-03-22 17:33:47 -0700480 surfaceFormat = userFormat;
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
Zhijun He916d8ac2017-03-22 17:33:47 -0700487 if (!isFormatOpaque(surfaceFormat)) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800488 res = native_window_set_usage(anw.get(), GRALLOC_USAGE_SW_WRITE_OFTEN);
489 if (res != OK) {
490 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
Dan Albert1102e212015-06-09 17:35:38 -0700491 __FUNCTION__, static_cast<unsigned int>(GRALLOC_USAGE_SW_WRITE_OFTEN),
Zhijun He916d8ac2017-03-22 17:33:47 -0700492 surfaceFormat, strerror(-res), res);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800493 jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
494 return 0;
495 }
496 }
497
498 int minUndequeuedBufferCount = 0;
499 res = anw->query(anw.get(),
500 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
501 if (res != OK) {
502 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
503 __FUNCTION__, strerror(-res), res);
504 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
505 return 0;
506 }
507
508 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
509 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
510 if (res != OK) {
511 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
512 jniThrowRuntimeException(env, "Set buffer count failed");
513 return 0;
514 }
515
516 if (ctx != 0) {
517 ctx->incStrong((void*)ImageWriter_init);
518 }
519 return nativeCtx;
520}
521
522static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
523 ALOGV("%s", __FUNCTION__);
524 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
525 if (ctx == NULL || thiz == NULL) {
526 jniThrowException(env, "java/lang/IllegalStateException",
527 "ImageWriterContext is not initialized");
528 return;
529 }
530
531 sp<ANativeWindow> anw = ctx->getProducer();
532 android_native_buffer_t *anb = NULL;
533 int fenceFd = -1;
534 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
535 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700536 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700537 switch (res) {
538 case NO_INIT:
539 jniThrowException(env, "java/lang/IllegalStateException",
540 "Surface has been abandoned");
541 break;
542 default:
543 // TODO: handle other error cases here.
544 jniThrowRuntimeException(env, "dequeue buffer failed");
545 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800546 return;
547 }
548 // New GraphicBuffer object doesn't own the handle, thus the native buffer
549 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700550 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800551
552 // Note that:
553 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
554 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
555 // later.
556 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
557
558 // Finally, set the native info into image object.
Sally Qiac97f992021-10-11 17:39:54 -0700559 Image_setNativeContext(env, image, buffer, fenceFd, ctx->getBufferDataSpace());
Zhijun Hef6a09e52015-02-24 18:12:23 -0800560}
561
562static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
563 ALOGV("%s:", __FUNCTION__);
564 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
565 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700566 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800567 return;
568 }
569
570 ANativeWindow* producer = ctx->getProducer();
571 if (producer != NULL) {
572 /**
573 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
574 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
575 * The producer listener will be cleared after disconnect call.
576 */
577 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
578 /**
579 * This is not an error. if client calling process dies, the window will
580 * also die and all calls to it will return DEAD_OBJECT, thus it's already
581 * "disconnected"
582 */
583 if (res == DEAD_OBJECT) {
584 ALOGW("%s: While disconnecting ImageWriter from native window, the"
585 " native window died already", __FUNCTION__);
586 } else if (res != OK) {
587 ALOGE("%s: native window disconnect failed: %s (%d)",
588 __FUNCTION__, strerror(-res), res);
589 jniThrowRuntimeException(env, "Native window disconnect failed");
590 return;
591 }
592 }
593
594 ctx->decStrong((void*)ImageWriter_init);
595}
596
597static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
598 ALOGV("%s", __FUNCTION__);
599 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
600 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800601 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800602 return;
603 }
604
605 sp<ANativeWindow> anw = ctx->getProducer();
606
607 GraphicBuffer *buffer = NULL;
608 int fenceFd = -1;
609 Image_getNativeContext(env, image, &buffer, &fenceFd);
610 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800611 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800612 return;
613 }
614
615 // Unlock the image if it was locked
616 Image_unlockIfLocked(env, image);
617
618 anw->cancelBuffer(anw.get(), buffer, fenceFd);
619
Sally Qiac97f992021-10-11 17:39:54 -0700620 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800621}
622
623static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
Sally Qiac97f992021-10-11 17:39:54 -0700624 jlong timestampNs, jlong dataSpace, jint left, jint top, jint right,
625 jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800626 ALOGV("%s", __FUNCTION__);
627 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
628 if (ctx == NULL || thiz == NULL) {
629 jniThrowException(env, "java/lang/IllegalStateException",
630 "ImageWriterContext is not initialized");
631 return;
632 }
633
634 status_t res = OK;
635 sp<ANativeWindow> anw = ctx->getProducer();
636
637 GraphicBuffer *buffer = NULL;
638 int fenceFd = -1;
639 Image_getNativeContext(env, image, &buffer, &fenceFd);
640 if (buffer == NULL) {
641 jniThrowException(env, "java/lang/IllegalStateException",
642 "Image is not initialized");
643 return;
644 }
645
646 // Unlock image if it was locked.
647 Image_unlockIfLocked(env, image);
648
649 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700650 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800651 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
652 if (res != OK) {
653 jniThrowRuntimeException(env, "Set timestamp failed");
654 return;
655 }
656
Sally Qiac97f992021-10-11 17:39:54 -0700657 // Set dataSpace
658 ALOGV("dataSpace to be queued: %" PRId64, dataSpace);
659 res = native_window_set_buffers_data_space(
660 anw.get(), static_cast<android_dataspace>(dataSpace));
661 if (res != OK) {
662 jniThrowRuntimeException(env, "Set dataspace failed");
663 return;
664 }
665
Zhijun Hef6a09e52015-02-24 18:12:23 -0800666 // Set crop
667 android_native_rect_t cropRect;
668 cropRect.left = left;
669 cropRect.top = top;
670 cropRect.right = right;
671 cropRect.bottom = bottom;
672 res = native_window_set_crop(anw.get(), &cropRect);
673 if (res != OK) {
674 jniThrowRuntimeException(env, "Set crop rect failed");
675 return;
676 }
677
Emilian Peev450a5ff2018-03-19 16:05:10 +0000678 res = native_window_set_buffers_transform(anw.get(), transform);
679 if (res != OK) {
680 jniThrowRuntimeException(env, "Set transform failed");
681 return;
682 }
683
Emilian Peev750aec62018-04-06 12:55:00 +0100684 res = native_window_set_scaling_mode(anw.get(), scalingMode);
685 if (res != OK) {
686 jniThrowRuntimeException(env, "Set scaling mode failed");
687 return;
688 }
689
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700690 // Finally, queue input buffer.
691 //
692 // Because onBufferReleased may be called before queueBuffer() returns,
693 // queue the "attached" flag before calling queueBuffer. In case
694 // queueBuffer() fails, remove it from the queue.
695 ctx->queueAttachedFlag(false);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800696 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
697 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700698 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700699 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700700 switch (res) {
701 case NO_INIT:
702 jniThrowException(env, "java/lang/IllegalStateException",
703 "Surface has been abandoned");
704 break;
705 default:
706 // TODO: handle other error cases here.
707 jniThrowRuntimeException(env, "Queue input buffer failed");
708 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800709 return;
710 }
711
Zhijun Hece9d6f92015-03-29 16:33:59 -0700712 // Clear the image native context: end of this image's lifecycle in public API.
Sally Qiac97f992021-10-11 17:39:54 -0700713 Image_setNativeContext(env, image, NULL, -1, HAL_DATASPACE_UNKNOWN);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800714}
715
Emilian Peev9c778e12020-10-29 17:36:22 -0700716static status_t attachAndQeueuGraphicBuffer(JNIEnv* env, JNIImageWriterContext *ctx,
Sally Qiac97f992021-10-11 17:39:54 -0700717 sp<Surface> surface, sp<GraphicBuffer> gb, jlong timestampNs, jlong dataSpace,
718 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700719 status_t res = OK;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700720 // Step 1. Attach Image
Emilian Peev9c778e12020-10-29 17:36:22 -0700721 res = surface->attachBuffer(gb.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700722 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700723 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700724 switch (res) {
725 case NO_INIT:
726 jniThrowException(env, "java/lang/IllegalStateException",
727 "Surface has been abandoned");
728 break;
729 default:
730 // TODO: handle other error cases here.
731 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
732 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700733 return res;
734 }
735 sp < ANativeWindow > anw = surface;
736
Sally Qiac97f992021-10-11 17:39:54 -0700737 // Step 2. Set timestamp, dataspace, crop, transform and scaling mode.
738 // Note that we do not need unlock the image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700739 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
740 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
741 if (res != OK) {
742 jniThrowRuntimeException(env, "Set timestamp failed");
743 return res;
744 }
745
Sally Qiac97f992021-10-11 17:39:54 -0700746 ALOGV("dataSpace to be queued: %" PRId64, dataSpace);
747 res = native_window_set_buffers_data_space(
748 anw.get(), static_cast<android_dataspace>(dataSpace));
749 if (res != OK) {
750 jniThrowRuntimeException(env, "Set dataSpace failed");
751 return res;
752 }
753
Zhijun Hece9d6f92015-03-29 16:33:59 -0700754 android_native_rect_t cropRect;
755 cropRect.left = left;
756 cropRect.top = top;
757 cropRect.right = right;
758 cropRect.bottom = bottom;
759 res = native_window_set_crop(anw.get(), &cropRect);
760 if (res != OK) {
761 jniThrowRuntimeException(env, "Set crop rect failed");
762 return res;
763 }
764
Emilian Peev450a5ff2018-03-19 16:05:10 +0000765 res = native_window_set_buffers_transform(anw.get(), transform);
766 if (res != OK) {
767 jniThrowRuntimeException(env, "Set transform failed");
768 return res;
769 }
770
Emilian Peev750aec62018-04-06 12:55:00 +0100771 res = native_window_set_scaling_mode(anw.get(), scalingMode);
772 if (res != OK) {
773 jniThrowRuntimeException(env, "Set scaling mode failed");
774 return res;
775 }
776
Zhijun Hece9d6f92015-03-29 16:33:59 -0700777 // Step 3. Queue Image.
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700778 //
779 // Because onBufferReleased may be called before queueBuffer() returns,
780 // queue the "attached" flag before calling queueBuffer. In case
781 // queueBuffer() fails, remove it from the queue.
782 ctx->queueAttachedFlag(true);
Emilian Peev9c778e12020-10-29 17:36:22 -0700783 res = anw->queueBuffer(anw.get(), gb.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700784 -1);
785 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700786 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700787 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700788 switch (res) {
789 case NO_INIT:
790 jniThrowException(env, "java/lang/IllegalStateException",
791 "Surface has been abandoned");
792 break;
793 default:
794 // TODO: handle other error cases here.
795 jniThrowRuntimeException(env, "Queue input buffer failed");
796 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700797 return res;
798 }
799
800 // Do not set the image native context. Since it would overwrite the existing native context
801 // of the image that is from ImageReader, the subsequent image close will run into issues.
802
803 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800804}
805
Emilian Peev9c778e12020-10-29 17:36:22 -0700806static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qiac97f992021-10-11 17:39:54 -0700807 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jlong dataSpace,
808 jint left, jint top, jint right, jint bottom, jint transform, jint scalingMode) {
Emilian Peev9c778e12020-10-29 17:36:22 -0700809 ALOGV("%s", __FUNCTION__);
810 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
811 if (ctx == NULL || thiz == NULL) {
812 jniThrowException(env, "java/lang/IllegalStateException",
813 "ImageWriterContext is not initialized");
814 return -1;
815 }
816
817 sp<Surface> surface = ctx->getProducer();
818 if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
819 jniThrowException(env, "java/lang/IllegalStateException",
820 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
821 return -1;
822 }
823
824 // Image is guaranteed to be from ImageReader at this point, so it is safe to
825 // cast to BufferItem pointer.
826 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
827 if (buffer == NULL) {
828 jniThrowException(env, "java/lang/IllegalStateException",
829 "Image is not initialized or already closed");
830 return -1;
831 }
832
Sally Qiac97f992021-10-11 17:39:54 -0700833 return attachAndQeueuGraphicBuffer(env, ctx, surface, buffer->mGraphicBuffer, timestampNs,
834 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700835}
836
837static jint ImageWriter_attachAndQueueGraphicBuffer(JNIEnv* env, jobject thiz, jlong nativeCtx,
Sally Qiac97f992021-10-11 17:39:54 -0700838 jobject buffer, jint format, jlong timestampNs, jlong dataSpace, jint left, jint top,
Emilian Peev9c778e12020-10-29 17:36:22 -0700839 jint right, jint bottom, jint transform, jint scalingMode) {
840 ALOGV("%s", __FUNCTION__);
841 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
842 if (ctx == NULL || thiz == NULL) {
843 jniThrowException(env, "java/lang/IllegalStateException",
844 "ImageWriterContext is not initialized");
845 return -1;
846 }
847
848 sp<Surface> surface = ctx->getProducer();
849 if (isFormatOpaque(format) != isFormatOpaque(ctx->getBufferFormat())) {
850 jniThrowException(env, "java/lang/IllegalStateException",
851 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
852 return -1;
853 }
854
855 sp<GraphicBuffer> graphicBuffer = android_graphics_GraphicBuffer_getNativeGraphicsBuffer(env,
856 buffer);
857 if (graphicBuffer.get() == NULL) {
858 jniThrowException(env, "java/lang/IllegalArgumentException",
859 "Trying to attach an invalid graphic buffer");
860 return -1;
861 }
Sally Qiac97f992021-10-11 17:39:54 -0700862 return attachAndQeueuGraphicBuffer(env, ctx, surface, graphicBuffer, timestampNs,
863 dataSpace, left, top, right, bottom, transform, scalingMode);
Emilian Peev9c778e12020-10-29 17:36:22 -0700864}
865
Zhijun Hef6a09e52015-02-24 18:12:23 -0800866// --------------------------Image methods---------------------------------------
867
868static void Image_getNativeContext(JNIEnv* env, jobject thiz,
869 GraphicBuffer** buffer, int* fenceFd) {
870 ALOGV("%s", __FUNCTION__);
871 if (buffer != NULL) {
872 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
873 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
874 *buffer = gb;
875 }
876
877 if (fenceFd != NULL) {
878 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
879 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
880 }
881}
882
883static void Image_setNativeContext(JNIEnv* env, jobject thiz,
Sally Qiac97f992021-10-11 17:39:54 -0700884 sp<GraphicBuffer> buffer, int fenceFd, long dataSpace) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800885 ALOGV("%s:", __FUNCTION__);
886 GraphicBuffer* p = NULL;
887 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
888 if (buffer != 0) {
889 buffer->incStrong((void*)Image_setNativeContext);
890 }
891 if (p) {
892 p->decStrong((void*)Image_setNativeContext);
893 }
894 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
895 reinterpret_cast<jlong>(buffer.get()));
896
897 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
Sally Qiac97f992021-10-11 17:39:54 -0700898
899 env->SetLongField(thiz, gSurfaceImageClassInfo.mDataSpace, dataSpace);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800900}
901
902static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
903 ALOGV("%s", __FUNCTION__);
904 GraphicBuffer* buffer;
905 Image_getNativeContext(env, thiz, &buffer, NULL);
906 if (buffer == NULL) {
907 jniThrowException(env, "java/lang/IllegalStateException",
908 "Image is not initialized");
909 return;
910 }
911
912 // Is locked?
913 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700914 jobject planes = NULL;
915 if (!isFormatOpaque(buffer->getPixelFormat())) {
916 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
917 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800918 isLocked = (planes != NULL);
919 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700920 // 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 -0800921 status_t res = buffer->unlock();
922 if (res != OK) {
923 jniThrowRuntimeException(env, "unlock buffer failed");
John Reckdcd4c582019-07-12 13:13:05 -0700924 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800925 }
926 ALOGV("Successfully unlocked the image");
927 }
928}
929
930static jint Image_getWidth(JNIEnv* env, jobject thiz) {
931 ALOGV("%s", __FUNCTION__);
932 GraphicBuffer* buffer;
933 Image_getNativeContext(env, thiz, &buffer, NULL);
934 if (buffer == NULL) {
935 jniThrowException(env, "java/lang/IllegalStateException",
936 "Image is not initialized");
937 return -1;
938 }
939
940 return buffer->getWidth();
941}
942
943static jint Image_getHeight(JNIEnv* env, jobject thiz) {
944 ALOGV("%s", __FUNCTION__);
945 GraphicBuffer* buffer;
946 Image_getNativeContext(env, thiz, &buffer, NULL);
947 if (buffer == NULL) {
948 jniThrowException(env, "java/lang/IllegalStateException",
949 "Image is not initialized");
950 return -1;
951 }
952
953 return buffer->getHeight();
954}
955
Zhijun Hef6a09e52015-02-24 18:12:23 -0800956static jint Image_getFormat(JNIEnv* env, jobject thiz) {
957 ALOGV("%s", __FUNCTION__);
958 GraphicBuffer* buffer;
959 Image_getNativeContext(env, thiz, &buffer, NULL);
960 if (buffer == NULL) {
961 jniThrowException(env, "java/lang/IllegalStateException",
962 "Image is not initialized");
963 return 0;
964 }
965
Zhijun He0ab41622016-02-25 16:00:38 -0800966 // ImageWriter doesn't support data space yet, assuming it is unknown.
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100967 PublicFormat publicFmt = mapHalFormatDataspaceToPublicFormat(buffer->getPixelFormat(),
968 HAL_DATASPACE_UNKNOWN);
Zhijun He0ab41622016-02-25 16:00:38 -0800969 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800970}
971
rennbe092192018-05-07 10:18:05 -0700972static jobject Image_getHardwareBuffer(JNIEnv* env, jobject thiz) {
973 GraphicBuffer* buffer;
974 Image_getNativeContext(env, thiz, &buffer, NULL);
975 if (buffer == NULL) {
976 jniThrowException(env, "java/lang/IllegalStateException",
977 "Image is not initialized");
978 return NULL;
979 }
980 AHardwareBuffer* b = AHardwareBuffer_from_GraphicBuffer(buffer);
981 // don't user the public AHardwareBuffer_toHardwareBuffer() because this would force us
982 // to link against libandroid.so
983 return android_hardware_HardwareBuffer_createFromAHardwareBuffer(env, b);
984}
985
Zhijun Hef6a09e52015-02-24 18:12:23 -0800986static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
987 ALOGV("%s:", __FUNCTION__);
988 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
989}
990
991static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
992 ALOGV("%s", __FUNCTION__);
993 GraphicBuffer* buffer;
994 int fenceFd = -1;
995 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
996 if (buffer == NULL) {
997 jniThrowException(env, "java/lang/IllegalStateException",
998 "Image is not initialized");
999 return;
1000 }
1001
Zhijun He0ab41622016-02-25 16:00:38 -08001002 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
1003 const Rect noCrop(buffer->width, buffer->height);
1004 status_t res = lockImageFromBuffer(
1005 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
1006 // Clear the fenceFd as it is already consumed by lock call.
1007 Image_setFenceFd(env, thiz, /*fenceFd*/-1);
1008 if (res != OK) {
1009 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
1010 "lock buffer failed for format 0x%x",
1011 buffer->getPixelFormat());
1012 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001013 }
1014
Zhijun He0ab41622016-02-25 16:00:38 -08001015 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001016 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
1017 // and we don't set them here.
1018}
1019
John Reckdcd4c582019-07-12 13:13:05 -07001020static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
Zhijun Hef6a09e52015-02-24 18:12:23 -08001021 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
1022 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001023
Zhijun He0ab41622016-02-25 16:00:38 -08001024 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
1025 pixelStride, rowStride);
1026 if (res != OK) {
1027 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
John Reck03bd07a2019-07-12 13:53:04 -07001028 "Pixel format: 0x%x is unsupported", writerFormat);
John Reckdcd4c582019-07-12 13:13:05 -07001029 return false;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001030 }
John Reckdcd4c582019-07-12 13:13:05 -07001031 return true;
Zhijun Hef6a09e52015-02-24 18:12:23 -08001032}
1033
1034static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
1035 int numPlanes, int writerFormat) {
1036 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
1037 int rowStride, pixelStride;
1038 uint8_t *pData;
1039 uint32_t dataSize;
1040 jobject byteBuffer;
1041
1042 int format = Image_getFormat(env, thiz);
Zhijun Hece9d6f92015-03-29 16:33:59 -07001043 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -08001044 String8 msg;
1045 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
1046 " must be 0", format, numPlanes);
1047 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
1048 return NULL;
1049 }
1050
1051 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
1052 /*initial_element*/NULL);
1053 if (surfacePlanes == NULL) {
1054 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
1055 " probably out of memory");
1056 return NULL;
1057 }
Zhijun Hece9d6f92015-03-29 16:33:59 -07001058 if (isFormatOpaque(format)) {
1059 return surfacePlanes;
1060 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001061
1062 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
1063 LockedImage lockedImg = LockedImage();
1064 Image_getLockedImage(env, thiz, &lockedImg);
1065
1066 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -08001067 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
Fedor Kudasov4d027e92019-06-24 17:21:57 +01001068 writerFormat = mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -08001069 for (int i = 0; i < numPlanes; i++) {
John Reckdcd4c582019-07-12 13:13:05 -07001070 if (!Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
1071 &pData, &dataSize, &pixelStride, &rowStride)) {
1072 return NULL;
1073 }
Zhijun Hef6a09e52015-02-24 18:12:23 -08001074 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1075 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1076 jniThrowException(env, "java/lang/IllegalStateException",
1077 "Failed to allocate ByteBuffer");
1078 return NULL;
1079 }
1080
1081 // Finally, create this SurfacePlane.
1082 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1083 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1084 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1085 }
1086
1087 return surfacePlanes;
1088}
1089
Zhijun Hef6a09e52015-02-24 18:12:23 -08001090} // extern "C"
1091
1092// ----------------------------------------------------------------------------
1093
1094static JNINativeMethod gImageWriterMethods[] = {
1095 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
Emilian Peevab808242020-12-28 16:03:32 -08001096 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;IIII)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -08001097 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -07001098 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Sally Qiac97f992021-10-11 17:39:54 -07001099 {"nativeAttachAndQueueImage",
1100 "(JJIJJIIIIII)I",
1101 (void*)ImageWriter_attachAndQueueImage },
Emilian Peev9c778e12020-10-29 17:36:22 -07001102 {"nativeAttachAndQueueGraphicBuffer",
Sally Qiac97f992021-10-11 17:39:54 -07001103 "(JLandroid/graphics/GraphicBuffer;IJJIIIIII)I",
Emilian Peev9c778e12020-10-29 17:36:22 -07001104 (void*)ImageWriter_attachAndQueueGraphicBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001105 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
Sally Qiac97f992021-10-11 17:39:54 -07001106 {"nativeQueueInputImage", "(JLandroid/media/Image;JJIIIIII)V",
1107 (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001108 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
1109};
1110
1111static JNINativeMethod gImageMethods[] = {
1112 {"nativeCreatePlanes", "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
rennbe092192018-05-07 10:18:05 -07001113 (void*)Image_createSurfacePlanes },
1114 {"nativeGetWidth", "()I", (void*)Image_getWidth },
1115 {"nativeGetHeight", "()I", (void*)Image_getHeight },
1116 {"nativeGetFormat", "()I", (void*)Image_getFormat },
1117 {"nativeGetHardwareBuffer", "()Landroid/hardware/HardwareBuffer;",
1118 (void*)Image_getHardwareBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001119};
1120
1121int register_android_media_ImageWriter(JNIEnv *env) {
1122
1123 int ret1 = AndroidRuntime::registerNativeMethods(env,
1124 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1125
1126 int ret2 = AndroidRuntime::registerNativeMethods(env,
1127 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1128
1129 return (ret1 || ret2);
1130}