blob: 936edb3fb005813b31d9bb529bc5dc3c618d5aef [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>
rennbe092192018-05-07 10:18:05 -070032#include <android_runtime/android_hardware_HardwareBuffer.h>
33#include <private/android/AHardwareBufferHelpers.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080034#include <jni.h>
Steven Moreland2279b252017-07-19 09:50:45 -070035#include <nativehelper/JNIHelp.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080036
37#include <stdint.h>
38#include <inttypes.h>
rennbe092192018-05-07 10:18:05 -070039#include <android/hardware_buffer_jni.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080040
Yin-Chia Yeh6132b022019-02-14 16:40:20 -080041#include <deque>
42
Zhijun Hef6a09e52015-02-24 18:12:23 -080043#define IMAGE_BUFFER_JNI_ID "mNativeBuffer"
Zhijun He916d8ac2017-03-22 17:33:47 -070044#define IMAGE_FORMAT_UNKNOWN 0 // This is the same value as ImageFormat#UNKNOWN.
Zhijun Hef6a09e52015-02-24 18:12:23 -080045// ----------------------------------------------------------------------------
46
47using namespace android;
48
Zhijun Hef6a09e52015-02-24 18:12:23 -080049static struct {
50 jmethodID postEventFromNative;
51 jfieldID mWriterFormat;
52} gImageWriterClassInfo;
53
54static struct {
55 jfieldID mNativeBuffer;
56 jfieldID mNativeFenceFd;
57 jfieldID mPlanes;
58} gSurfaceImageClassInfo;
59
60static struct {
61 jclass clazz;
62 jmethodID ctor;
63} gSurfacePlaneClassInfo;
64
Zhijun Hef6a09e52015-02-24 18:12:23 -080065// ----------------------------------------------------------------------------
66
67class JNIImageWriterContext : public BnProducerListener {
68public:
69 JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz);
70
71 virtual ~JNIImageWriterContext();
72
73 // Implementation of IProducerListener, used to notify the ImageWriter that the consumer
74 // has returned a buffer and it is ready for ImageWriter to dequeue.
75 virtual void onBufferReleased();
76
Zhijun Hece9d6f92015-03-29 16:33:59 -070077 void setProducer(const sp<Surface>& producer) { mProducer = producer; }
78 Surface* getProducer() { return mProducer.get(); }
Zhijun Hef6a09e52015-02-24 18:12:23 -080079
80 void setBufferFormat(int format) { mFormat = format; }
81 int getBufferFormat() { return mFormat; }
82
83 void setBufferWidth(int width) { mWidth = width; }
84 int getBufferWidth() { return mWidth; }
85
86 void setBufferHeight(int height) { mHeight = height; }
87 int getBufferHeight() { return mHeight; }
88
Shuzhen Wangb9adb572020-06-24 09:33:27 -070089 void queueAttachedFlag(bool isAttached) {
90 Mutex::Autolock l(mAttachedFlagQueueLock);
91 mAttachedFlagQueue.push_back(isAttached);
92 }
93 void dequeueAttachedFlag() {
94 Mutex::Autolock l(mAttachedFlagQueueLock);
95 mAttachedFlagQueue.pop_back();
96 }
Zhijun Hef6a09e52015-02-24 18:12:23 -080097private:
98 static JNIEnv* getJNIEnv(bool* needsDetach);
99 static void detachJNI();
100
Zhijun Hece9d6f92015-03-29 16:33:59 -0700101 sp<Surface> mProducer;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800102 jobject mWeakThiz;
103 jclass mClazz;
104 int mFormat;
105 int mWidth;
106 int mHeight;
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800107
108 // Class for a shared thread used to detach buffers from buffer queues
109 // to discard buffers after consumers are done using them.
110 // This is needed because detaching buffers in onBufferReleased callback
111 // can lead to deadlock when consumer/producer are on the same process.
112 class BufferDetacher {
113 public:
114 // Called by JNIImageWriterContext ctor. Will start the thread for first ref.
115 void addRef();
116 // Called by JNIImageWriterContext dtor. Will stop the thread after ref goes to 0.
117 void removeRef();
118 // Called by onBufferReleased to signal this thread to detach a buffer
119 void detach(wp<Surface>);
120
121 private:
122
123 class DetachThread : public Thread {
124 public:
125 DetachThread() : Thread(/*canCallJava*/false) {};
126
127 void detach(wp<Surface>);
128
129 virtual void requestExit() override;
130
131 private:
132 virtual bool threadLoop() override;
133
134 Mutex mLock;
135 Condition mCondition;
136 std::deque<wp<Surface>> mQueue;
137
Yin-Chia Yehedace1a2019-07-30 13:02:59 -0700138 static const nsecs_t kWaitDuration = 500000000; // 500 ms
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800139 };
140 sp<DetachThread> mThread;
141
142 Mutex mLock;
143 int mRefCount = 0;
144 };
145
146 static BufferDetacher sBufferDetacher;
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700147
148 // Buffer queue guarantees both producer and consumer side buffer flows are
149 // in order. See b/19977520. As a result, we can use a queue here.
150 Mutex mAttachedFlagQueueLock;
151 std::deque<bool> mAttachedFlagQueue;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800152};
153
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800154JNIImageWriterContext::BufferDetacher JNIImageWriterContext::sBufferDetacher;
155
156void JNIImageWriterContext::BufferDetacher::addRef() {
157 Mutex::Autolock l(mLock);
158 mRefCount++;
159 if (mRefCount == 1) {
160 mThread = new DetachThread();
161 mThread->run("BufDtchThrd");
162 }
163}
164
165void JNIImageWriterContext::BufferDetacher::removeRef() {
166 Mutex::Autolock l(mLock);
167 mRefCount--;
168 if (mRefCount == 0) {
169 mThread->requestExit();
170 mThread->join();
171 mThread.clear();
172 }
173}
174
175void JNIImageWriterContext::BufferDetacher::detach(wp<Surface> bq) {
176 Mutex::Autolock l(mLock);
177 if (mThread == nullptr) {
178 ALOGE("%s: buffer detach thread is gone!", __FUNCTION__);
179 return;
180 }
181 mThread->detach(bq);
182}
183
184void JNIImageWriterContext::BufferDetacher::DetachThread::detach(wp<Surface> bq) {
185 Mutex::Autolock l(mLock);
186 mQueue.push_back(bq);
187 mCondition.signal();
188}
189
190void JNIImageWriterContext::BufferDetacher::DetachThread::requestExit() {
191 Thread::requestExit();
192 {
193 Mutex::Autolock l(mLock);
194 mQueue.clear();
195 }
196 mCondition.signal();
197}
198
199bool JNIImageWriterContext::BufferDetacher::DetachThread::threadLoop() {
200 Mutex::Autolock l(mLock);
201 mCondition.waitRelative(mLock, kWaitDuration);
202
203 while (!mQueue.empty()) {
204 if (exitPending()) {
205 return false;
206 }
207
208 wp<Surface> wbq = mQueue.front();
209 mQueue.pop_front();
210 sp<Surface> bq = wbq.promote();
211 if (bq != nullptr) {
212 sp<Fence> fence;
213 sp<GraphicBuffer> buffer;
214 ALOGV("%s: One buffer is detached", __FUNCTION__);
215 mLock.unlock();
216 bq->detachNextBuffer(&buffer, &fence);
217 mLock.lock();
218 }
219 }
220 return !exitPending();
221}
222
Zhijun Hef6a09e52015-02-24 18:12:23 -0800223JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800224 mWeakThiz(env->NewGlobalRef(weakThiz)),
225 mClazz((jclass)env->NewGlobalRef(clazz)),
226 mFormat(0),
227 mWidth(-1),
228 mHeight(-1) {
229 sBufferDetacher.addRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800230}
231
232JNIImageWriterContext::~JNIImageWriterContext() {
233 ALOGV("%s", __FUNCTION__);
234 bool needsDetach = false;
235 JNIEnv* env = getJNIEnv(&needsDetach);
236 if (env != NULL) {
237 env->DeleteGlobalRef(mWeakThiz);
238 env->DeleteGlobalRef(mClazz);
239 } else {
240 ALOGW("leaking JNI object references");
241 }
242 if (needsDetach) {
243 detachJNI();
244 }
245
246 mProducer.clear();
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800247 sBufferDetacher.removeRef();
Zhijun Hef6a09e52015-02-24 18:12:23 -0800248}
249
250JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
251 ALOGV("%s", __FUNCTION__);
252 LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
253 *needsDetach = false;
254 JNIEnv* env = AndroidRuntime::getJNIEnv();
255 if (env == NULL) {
256 JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
257 JavaVM* vm = AndroidRuntime::getJavaVM();
258 int result = vm->AttachCurrentThread(&env, (void*) &args);
259 if (result != JNI_OK) {
260 ALOGE("thread attach failed: %#x", result);
261 return NULL;
262 }
263 *needsDetach = true;
264 }
265 return env;
266}
267
268void JNIImageWriterContext::detachJNI() {
269 ALOGV("%s", __FUNCTION__);
270 JavaVM* vm = AndroidRuntime::getJavaVM();
271 int result = vm->DetachCurrentThread();
272 if (result != JNI_OK) {
273 ALOGE("thread detach failed: %#x", result);
274 }
275}
276
277void JNIImageWriterContext::onBufferReleased() {
278 ALOGV("%s: buffer released", __FUNCTION__);
279 bool needsDetach = false;
280 JNIEnv* env = getJNIEnv(&needsDetach);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700281
282 bool bufferIsAttached = false;
283 {
284 Mutex::Autolock l(mAttachedFlagQueueLock);
285 if (!mAttachedFlagQueue.empty()) {
286 bufferIsAttached = mAttachedFlagQueue.front();
287 mAttachedFlagQueue.pop_front();
288 } else {
289 ALOGW("onBufferReleased called with no attached flag queued");
290 }
291 }
292
Zhijun Hef6a09e52015-02-24 18:12:23 -0800293 if (env != NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700294 // Detach the buffer every time when a buffer consumption is done,
295 // need let this callback give a BufferItem, then only detach if it was attached to this
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700296 // Writer. see b/19977520
297 if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED || bufferIsAttached) {
Yin-Chia Yeh6132b022019-02-14 16:40:20 -0800298 sBufferDetacher.detach(mProducer);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700299 }
300
Zhijun Hef6a09e52015-02-24 18:12:23 -0800301 env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
302 } else {
303 ALOGW("onBufferReleased event will not posted");
304 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700305
Zhijun Hef6a09e52015-02-24 18:12:23 -0800306 if (needsDetach) {
307 detachJNI();
308 }
309}
310
311// ----------------------------------------------------------------------------
312
313extern "C" {
314
315// -------------------------------Private method declarations--------------
316
Zhijun Hef6a09e52015-02-24 18:12:23 -0800317static void Image_setNativeContext(JNIEnv* env, jobject thiz,
318 sp<GraphicBuffer> buffer, int fenceFd);
319static void Image_getNativeContext(JNIEnv* env, jobject thiz,
320 GraphicBuffer** buffer, int* fenceFd);
321static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
322
323// --------------------------ImageWriter methods---------------------------------------
324
325static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
326 ALOGV("%s:", __FUNCTION__);
327 jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
328 LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
329 "can't find android/media/ImageWriter$WriterSurfaceImage");
330 gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
331 imageClazz, IMAGE_BUFFER_JNI_ID, "J");
332 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
333 "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
334
335 gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
336 imageClazz, "mNativeFenceFd", "I");
337 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
338 "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
339
340 gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
341 imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
342 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
343 "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
344
345 gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
346 clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
347 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
348 "can't find android/media/ImageWriter.postEventFromNative");
349
350 gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
351 clazz, "mWriterFormat", "I");
352 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
353 "can't find android/media/ImageWriter.mWriterFormat");
354
355 jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
356 LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
357 // FindClass only gives a local reference of jclass object.
358 gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
359 gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
360 "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
361 LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
362 "Can not find SurfacePlane constructor");
363}
364
365static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
Zhijun He916d8ac2017-03-22 17:33:47 -0700366 jint maxImages, jint userFormat) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800367 status_t res;
368
369 ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
370
371 sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
372 if (surface == NULL) {
373 jniThrowException(env,
374 "java/lang/IllegalArgumentException",
375 "The surface has been released");
376 return 0;
377 }
378 sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
379
380 jclass clazz = env->GetObjectClass(thiz);
381 if (clazz == NULL) {
382 jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
383 return 0;
384 }
385 sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
386
387 sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
388 ctx->setProducer(producer);
389 /**
390 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
391 * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
392 * will be cleared after disconnect call.
393 */
Emilian Peev2adf4032018-06-05 17:52:16 +0100394 res = producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
395 if (res != OK) {
396 ALOGE("%s: Connecting to surface producer interface failed: %s (%d)",
397 __FUNCTION__, strerror(-res), res);
398 jniThrowRuntimeException(env, "Failed to connect to native window");
399 return 0;
400 }
401
Zhijun Hef6a09e52015-02-24 18:12:23 -0800402 jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
403
404 // Get the dimension and format of the producer.
405 sp<ANativeWindow> anw = producer;
Zhijun He916d8ac2017-03-22 17:33:47 -0700406 int32_t width, height, surfaceFormat;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800407 if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
408 ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
409 jniThrowRuntimeException(env, "Failed to query Surface width");
410 return 0;
411 }
412 ctx->setBufferWidth(width);
413
414 if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
415 ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
416 jniThrowRuntimeException(env, "Failed to query Surface height");
417 return 0;
418 }
419 ctx->setBufferHeight(height);
420
Zhijun He916d8ac2017-03-22 17:33:47 -0700421 // Query surface format if no valid user format is specified, otherwise, override surface format
422 // with user format.
423 if (userFormat == IMAGE_FORMAT_UNKNOWN) {
424 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceFormat)) != OK) {
425 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
426 jniThrowRuntimeException(env, "Failed to query Surface format");
427 return 0;
428 }
429 } else {
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700430 // Set consumer buffer format to user specified format
431 PublicFormat publicFormat = static_cast<PublicFormat>(userFormat);
432 int nativeFormat = mapPublicFormatToHalFormat(publicFormat);
433 android_dataspace nativeDataspace = mapPublicFormatToHalDataspace(publicFormat);
434 res = native_window_set_buffers_format(anw.get(), nativeFormat);
435 if (res != OK) {
436 ALOGE("%s: Unable to configure consumer native buffer format to %#x",
437 __FUNCTION__, nativeFormat);
438 jniThrowRuntimeException(env, "Failed to set Surface format");
439 return 0;
440 }
441
442 res = native_window_set_buffers_data_space(anw.get(), nativeDataspace);
443 if (res != OK) {
444 ALOGE("%s: Unable to configure consumer dataspace %#x",
445 __FUNCTION__, nativeDataspace);
446 jniThrowRuntimeException(env, "Failed to set Surface dataspace");
447 return 0;
448 }
Zhijun He916d8ac2017-03-22 17:33:47 -0700449 surfaceFormat = userFormat;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800450 }
Yin-Chia Yeh6dc192e2019-07-30 15:29:16 -0700451
Zhijun He916d8ac2017-03-22 17:33:47 -0700452 ctx->setBufferFormat(surfaceFormat);
453 env->SetIntField(thiz,
454 gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800455
Zhijun He916d8ac2017-03-22 17:33:47 -0700456 if (!isFormatOpaque(surfaceFormat)) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800457 res = native_window_set_usage(anw.get(), GRALLOC_USAGE_SW_WRITE_OFTEN);
458 if (res != OK) {
459 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
Dan Albert1102e212015-06-09 17:35:38 -0700460 __FUNCTION__, static_cast<unsigned int>(GRALLOC_USAGE_SW_WRITE_OFTEN),
Zhijun He916d8ac2017-03-22 17:33:47 -0700461 surfaceFormat, strerror(-res), res);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800462 jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
463 return 0;
464 }
465 }
466
467 int minUndequeuedBufferCount = 0;
468 res = anw->query(anw.get(),
469 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
470 if (res != OK) {
471 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
472 __FUNCTION__, strerror(-res), res);
473 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
474 return 0;
475 }
476
477 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
478 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
479 if (res != OK) {
480 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
481 jniThrowRuntimeException(env, "Set buffer count failed");
482 return 0;
483 }
484
485 if (ctx != 0) {
486 ctx->incStrong((void*)ImageWriter_init);
487 }
488 return nativeCtx;
489}
490
491static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
492 ALOGV("%s", __FUNCTION__);
493 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
494 if (ctx == NULL || thiz == NULL) {
495 jniThrowException(env, "java/lang/IllegalStateException",
496 "ImageWriterContext is not initialized");
497 return;
498 }
499
500 sp<ANativeWindow> anw = ctx->getProducer();
501 android_native_buffer_t *anb = NULL;
502 int fenceFd = -1;
503 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
504 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700505 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700506 switch (res) {
507 case NO_INIT:
508 jniThrowException(env, "java/lang/IllegalStateException",
509 "Surface has been abandoned");
510 break;
511 default:
512 // TODO: handle other error cases here.
513 jniThrowRuntimeException(env, "dequeue buffer failed");
514 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800515 return;
516 }
517 // New GraphicBuffer object doesn't own the handle, thus the native buffer
518 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700519 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800520
521 // Note that:
522 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
523 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
524 // later.
525 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
526
527 // Finally, set the native info into image object.
528 Image_setNativeContext(env, image, buffer, fenceFd);
529}
530
531static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
532 ALOGV("%s:", __FUNCTION__);
533 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
534 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700535 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800536 return;
537 }
538
539 ANativeWindow* producer = ctx->getProducer();
540 if (producer != NULL) {
541 /**
542 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
543 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
544 * The producer listener will be cleared after disconnect call.
545 */
546 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
547 /**
548 * This is not an error. if client calling process dies, the window will
549 * also die and all calls to it will return DEAD_OBJECT, thus it's already
550 * "disconnected"
551 */
552 if (res == DEAD_OBJECT) {
553 ALOGW("%s: While disconnecting ImageWriter from native window, the"
554 " native window died already", __FUNCTION__);
555 } else if (res != OK) {
556 ALOGE("%s: native window disconnect failed: %s (%d)",
557 __FUNCTION__, strerror(-res), res);
558 jniThrowRuntimeException(env, "Native window disconnect failed");
559 return;
560 }
561 }
562
563 ctx->decStrong((void*)ImageWriter_init);
564}
565
566static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
567 ALOGV("%s", __FUNCTION__);
568 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
569 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800570 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800571 return;
572 }
573
574 sp<ANativeWindow> anw = ctx->getProducer();
575
576 GraphicBuffer *buffer = NULL;
577 int fenceFd = -1;
578 Image_getNativeContext(env, image, &buffer, &fenceFd);
579 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800580 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800581 return;
582 }
583
584 // Unlock the image if it was locked
585 Image_unlockIfLocked(env, image);
586
587 anw->cancelBuffer(anw.get(), buffer, fenceFd);
588
589 Image_setNativeContext(env, image, NULL, -1);
590}
591
592static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
Emilian Peev750aec62018-04-06 12:55:00 +0100593 jlong timestampNs, jint left, jint top, jint right, jint bottom, jint transform,
594 jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800595 ALOGV("%s", __FUNCTION__);
596 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
597 if (ctx == NULL || thiz == NULL) {
598 jniThrowException(env, "java/lang/IllegalStateException",
599 "ImageWriterContext is not initialized");
600 return;
601 }
602
603 status_t res = OK;
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) {
610 jniThrowException(env, "java/lang/IllegalStateException",
611 "Image is not initialized");
612 return;
613 }
614
615 // Unlock image if it was locked.
616 Image_unlockIfLocked(env, image);
617
618 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700619 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800620 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
621 if (res != OK) {
622 jniThrowRuntimeException(env, "Set timestamp failed");
623 return;
624 }
625
626 // Set crop
627 android_native_rect_t cropRect;
628 cropRect.left = left;
629 cropRect.top = top;
630 cropRect.right = right;
631 cropRect.bottom = bottom;
632 res = native_window_set_crop(anw.get(), &cropRect);
633 if (res != OK) {
634 jniThrowRuntimeException(env, "Set crop rect failed");
635 return;
636 }
637
Emilian Peev450a5ff2018-03-19 16:05:10 +0000638 res = native_window_set_buffers_transform(anw.get(), transform);
639 if (res != OK) {
640 jniThrowRuntimeException(env, "Set transform failed");
641 return;
642 }
643
Emilian Peev750aec62018-04-06 12:55:00 +0100644 res = native_window_set_scaling_mode(anw.get(), scalingMode);
645 if (res != OK) {
646 jniThrowRuntimeException(env, "Set scaling mode failed");
647 return;
648 }
649
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700650 // Finally, queue input buffer.
651 //
652 // Because onBufferReleased may be called before queueBuffer() returns,
653 // queue the "attached" flag before calling queueBuffer. In case
654 // queueBuffer() fails, remove it from the queue.
655 ctx->queueAttachedFlag(false);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800656 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
657 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700658 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700659 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700660 switch (res) {
661 case NO_INIT:
662 jniThrowException(env, "java/lang/IllegalStateException",
663 "Surface has been abandoned");
664 break;
665 default:
666 // TODO: handle other error cases here.
667 jniThrowRuntimeException(env, "Queue input buffer failed");
668 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800669 return;
670 }
671
Zhijun Hece9d6f92015-03-29 16:33:59 -0700672 // Clear the image native context: end of this image's lifecycle in public API.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800673 Image_setNativeContext(env, image, NULL, -1);
674}
675
Zhijun Hece9d6f92015-03-29 16:33:59 -0700676static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
677 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint left, jint top,
Emilian Peev750aec62018-04-06 12:55:00 +0100678 jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800679 ALOGV("%s", __FUNCTION__);
680 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
681 if (ctx == NULL || thiz == NULL) {
682 jniThrowException(env, "java/lang/IllegalStateException",
683 "ImageWriterContext is not initialized");
Zhijun Hece9d6f92015-03-29 16:33:59 -0700684 return -1;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800685 }
686
Zhijun Hece9d6f92015-03-29 16:33:59 -0700687 sp<Surface> surface = ctx->getProducer();
688 status_t res = OK;
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700689 if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800690 jniThrowException(env, "java/lang/IllegalStateException",
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700691 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
Zhijun Hece9d6f92015-03-29 16:33:59 -0700692 return -1;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800693 }
694
Zhijun Hece9d6f92015-03-29 16:33:59 -0700695 // Image is guaranteed to be from ImageReader at this point, so it is safe to
696 // cast to BufferItem pointer.
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700697 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
698 if (buffer == NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700699 jniThrowException(env, "java/lang/IllegalStateException",
700 "Image is not initialized or already closed");
701 return -1;
702 }
703
704 // Step 1. Attach Image
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700705 res = surface->attachBuffer(buffer->mGraphicBuffer.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700706 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700707 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700708 switch (res) {
709 case NO_INIT:
710 jniThrowException(env, "java/lang/IllegalStateException",
711 "Surface has been abandoned");
712 break;
713 default:
714 // TODO: handle other error cases here.
715 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
716 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700717 return res;
718 }
719 sp < ANativeWindow > anw = surface;
720
Emilian Peev750aec62018-04-06 12:55:00 +0100721 // Step 2. Set timestamp, crop, transform and scaling mode. Note that we do not need unlock the
722 // image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700723 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
724 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
725 if (res != OK) {
726 jniThrowRuntimeException(env, "Set timestamp failed");
727 return res;
728 }
729
730 android_native_rect_t cropRect;
731 cropRect.left = left;
732 cropRect.top = top;
733 cropRect.right = right;
734 cropRect.bottom = bottom;
735 res = native_window_set_crop(anw.get(), &cropRect);
736 if (res != OK) {
737 jniThrowRuntimeException(env, "Set crop rect failed");
738 return res;
739 }
740
Emilian Peev450a5ff2018-03-19 16:05:10 +0000741 res = native_window_set_buffers_transform(anw.get(), transform);
742 if (res != OK) {
743 jniThrowRuntimeException(env, "Set transform failed");
744 return res;
745 }
746
Emilian Peev750aec62018-04-06 12:55:00 +0100747 res = native_window_set_scaling_mode(anw.get(), scalingMode);
748 if (res != OK) {
749 jniThrowRuntimeException(env, "Set scaling mode failed");
750 return res;
751 }
752
Zhijun Hece9d6f92015-03-29 16:33:59 -0700753 // Step 3. Queue Image.
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700754 //
755 // Because onBufferReleased may be called before queueBuffer() returns,
756 // queue the "attached" flag before calling queueBuffer. In case
757 // queueBuffer() fails, remove it from the queue.
758 ctx->queueAttachedFlag(true);
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700759 res = anw->queueBuffer(anw.get(), buffer->mGraphicBuffer.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700760 -1);
761 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700762 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Shuzhen Wangb9adb572020-06-24 09:33:27 -0700763 ctx->dequeueAttachedFlag();
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700764 switch (res) {
765 case NO_INIT:
766 jniThrowException(env, "java/lang/IllegalStateException",
767 "Surface has been abandoned");
768 break;
769 default:
770 // TODO: handle other error cases here.
771 jniThrowRuntimeException(env, "Queue input buffer failed");
772 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700773 return res;
774 }
775
776 // Do not set the image native context. Since it would overwrite the existing native context
777 // of the image that is from ImageReader, the subsequent image close will run into issues.
778
779 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800780}
781
782// --------------------------Image methods---------------------------------------
783
784static void Image_getNativeContext(JNIEnv* env, jobject thiz,
785 GraphicBuffer** buffer, int* fenceFd) {
786 ALOGV("%s", __FUNCTION__);
787 if (buffer != NULL) {
788 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
789 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
790 *buffer = gb;
791 }
792
793 if (fenceFd != NULL) {
794 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
795 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
796 }
797}
798
799static void Image_setNativeContext(JNIEnv* env, jobject thiz,
800 sp<GraphicBuffer> buffer, int fenceFd) {
801 ALOGV("%s:", __FUNCTION__);
802 GraphicBuffer* p = NULL;
803 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
804 if (buffer != 0) {
805 buffer->incStrong((void*)Image_setNativeContext);
806 }
807 if (p) {
808 p->decStrong((void*)Image_setNativeContext);
809 }
810 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
811 reinterpret_cast<jlong>(buffer.get()));
812
813 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
814}
815
816static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
817 ALOGV("%s", __FUNCTION__);
818 GraphicBuffer* buffer;
819 Image_getNativeContext(env, thiz, &buffer, NULL);
820 if (buffer == NULL) {
821 jniThrowException(env, "java/lang/IllegalStateException",
822 "Image is not initialized");
823 return;
824 }
825
826 // Is locked?
827 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700828 jobject planes = NULL;
829 if (!isFormatOpaque(buffer->getPixelFormat())) {
830 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
831 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800832 isLocked = (planes != NULL);
833 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700834 // 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 -0800835 status_t res = buffer->unlock();
836 if (res != OK) {
837 jniThrowRuntimeException(env, "unlock buffer failed");
John Reckdcd4c582019-07-12 13:13:05 -0700838 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800839 }
840 ALOGV("Successfully unlocked the image");
841 }
842}
843
844static jint Image_getWidth(JNIEnv* env, jobject thiz) {
845 ALOGV("%s", __FUNCTION__);
846 GraphicBuffer* buffer;
847 Image_getNativeContext(env, thiz, &buffer, NULL);
848 if (buffer == NULL) {
849 jniThrowException(env, "java/lang/IllegalStateException",
850 "Image is not initialized");
851 return -1;
852 }
853
854 return buffer->getWidth();
855}
856
857static jint Image_getHeight(JNIEnv* env, jobject thiz) {
858 ALOGV("%s", __FUNCTION__);
859 GraphicBuffer* buffer;
860 Image_getNativeContext(env, thiz, &buffer, NULL);
861 if (buffer == NULL) {
862 jniThrowException(env, "java/lang/IllegalStateException",
863 "Image is not initialized");
864 return -1;
865 }
866
867 return buffer->getHeight();
868}
869
Zhijun Hef6a09e52015-02-24 18:12:23 -0800870static jint Image_getFormat(JNIEnv* env, jobject thiz) {
871 ALOGV("%s", __FUNCTION__);
872 GraphicBuffer* buffer;
873 Image_getNativeContext(env, thiz, &buffer, NULL);
874 if (buffer == NULL) {
875 jniThrowException(env, "java/lang/IllegalStateException",
876 "Image is not initialized");
877 return 0;
878 }
879
Zhijun He0ab41622016-02-25 16:00:38 -0800880 // ImageWriter doesn't support data space yet, assuming it is unknown.
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100881 PublicFormat publicFmt = mapHalFormatDataspaceToPublicFormat(buffer->getPixelFormat(),
882 HAL_DATASPACE_UNKNOWN);
Zhijun He0ab41622016-02-25 16:00:38 -0800883 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800884}
885
rennbe092192018-05-07 10:18:05 -0700886static jobject Image_getHardwareBuffer(JNIEnv* env, jobject thiz) {
887 GraphicBuffer* buffer;
888 Image_getNativeContext(env, thiz, &buffer, NULL);
889 if (buffer == NULL) {
890 jniThrowException(env, "java/lang/IllegalStateException",
891 "Image is not initialized");
892 return NULL;
893 }
894 AHardwareBuffer* b = AHardwareBuffer_from_GraphicBuffer(buffer);
895 // don't user the public AHardwareBuffer_toHardwareBuffer() because this would force us
896 // to link against libandroid.so
897 return android_hardware_HardwareBuffer_createFromAHardwareBuffer(env, b);
898}
899
Zhijun Hef6a09e52015-02-24 18:12:23 -0800900static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
901 ALOGV("%s:", __FUNCTION__);
902 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
903}
904
905static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
906 ALOGV("%s", __FUNCTION__);
907 GraphicBuffer* buffer;
908 int fenceFd = -1;
909 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
910 if (buffer == NULL) {
911 jniThrowException(env, "java/lang/IllegalStateException",
912 "Image is not initialized");
913 return;
914 }
915
Zhijun He0ab41622016-02-25 16:00:38 -0800916 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
917 const Rect noCrop(buffer->width, buffer->height);
918 status_t res = lockImageFromBuffer(
919 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
920 // Clear the fenceFd as it is already consumed by lock call.
921 Image_setFenceFd(env, thiz, /*fenceFd*/-1);
922 if (res != OK) {
923 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
924 "lock buffer failed for format 0x%x",
925 buffer->getPixelFormat());
926 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800927 }
928
Zhijun He0ab41622016-02-25 16:00:38 -0800929 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800930 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
931 // and we don't set them here.
932}
933
John Reckdcd4c582019-07-12 13:13:05 -0700934static bool Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
Zhijun Hef6a09e52015-02-24 18:12:23 -0800935 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
936 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800937
Zhijun He0ab41622016-02-25 16:00:38 -0800938 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
939 pixelStride, rowStride);
940 if (res != OK) {
941 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
John Reck03bd07a2019-07-12 13:53:04 -0700942 "Pixel format: 0x%x is unsupported", writerFormat);
John Reckdcd4c582019-07-12 13:13:05 -0700943 return false;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800944 }
John Reckdcd4c582019-07-12 13:13:05 -0700945 return true;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800946}
947
948static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
949 int numPlanes, int writerFormat) {
950 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
951 int rowStride, pixelStride;
952 uint8_t *pData;
953 uint32_t dataSize;
954 jobject byteBuffer;
955
956 int format = Image_getFormat(env, thiz);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700957 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800958 String8 msg;
959 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
960 " must be 0", format, numPlanes);
961 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
962 return NULL;
963 }
964
965 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
966 /*initial_element*/NULL);
967 if (surfacePlanes == NULL) {
968 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
969 " probably out of memory");
970 return NULL;
971 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700972 if (isFormatOpaque(format)) {
973 return surfacePlanes;
974 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800975
976 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
977 LockedImage lockedImg = LockedImage();
978 Image_getLockedImage(env, thiz, &lockedImg);
979
980 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -0800981 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
Fedor Kudasov4d027e92019-06-24 17:21:57 +0100982 writerFormat = mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800983 for (int i = 0; i < numPlanes; i++) {
John Reckdcd4c582019-07-12 13:13:05 -0700984 if (!Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
985 &pData, &dataSize, &pixelStride, &rowStride)) {
986 return NULL;
987 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800988 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
989 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
990 jniThrowException(env, "java/lang/IllegalStateException",
991 "Failed to allocate ByteBuffer");
992 return NULL;
993 }
994
995 // Finally, create this SurfacePlane.
996 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
997 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
998 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
999 }
1000
1001 return surfacePlanes;
1002}
1003
Zhijun Hef6a09e52015-02-24 18:12:23 -08001004} // extern "C"
1005
1006// ----------------------------------------------------------------------------
1007
1008static JNINativeMethod gImageWriterMethods[] = {
1009 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
Zhijun He916d8ac2017-03-22 17:33:47 -07001010 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;II)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -08001011 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -07001012 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Emilian Peev750aec62018-04-06 12:55:00 +01001013 {"nativeAttachAndQueueImage", "(JJIJIIIIII)I", (void*)ImageWriter_attachAndQueueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001014 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
Emilian Peev750aec62018-04-06 12:55:00 +01001015 {"nativeQueueInputImage", "(JLandroid/media/Image;JIIIIII)V", (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001016 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
1017};
1018
1019static JNINativeMethod gImageMethods[] = {
1020 {"nativeCreatePlanes", "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
rennbe092192018-05-07 10:18:05 -07001021 (void*)Image_createSurfacePlanes },
1022 {"nativeGetWidth", "()I", (void*)Image_getWidth },
1023 {"nativeGetHeight", "()I", (void*)Image_getHeight },
1024 {"nativeGetFormat", "()I", (void*)Image_getFormat },
1025 {"nativeGetHardwareBuffer", "()Landroid/hardware/HardwareBuffer;",
1026 (void*)Image_getHardwareBuffer },
Zhijun Hef6a09e52015-02-24 18:12:23 -08001027};
1028
1029int register_android_media_ImageWriter(JNIEnv *env) {
1030
1031 int ret1 = AndroidRuntime::registerNativeMethods(env,
1032 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1033
1034 int ret2 = AndroidRuntime::registerNativeMethods(env,
1035 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1036
1037 return (ret1 || ret2);
1038}