blob: 11659e4826c547aba4a31e9dd7d5086c461dbb51 [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
Zhijun Hef6a09e52015-02-24 18:12:23 -080021#include <utils/Log.h>
22#include <utils/String8.h>
23
24#include <gui/IProducerListener.h>
25#include <gui/Surface.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080026#include <android_runtime/AndroidRuntime.h>
27#include <android_runtime/android_view_Surface.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080028#include <jni.h>
Steven Moreland2279b252017-07-19 09:50:45 -070029#include <nativehelper/JNIHelp.h>
Zhijun Hef6a09e52015-02-24 18:12:23 -080030
31#include <stdint.h>
32#include <inttypes.h>
33
Zhijun Hef6a09e52015-02-24 18:12:23 -080034#define IMAGE_BUFFER_JNI_ID "mNativeBuffer"
Zhijun He916d8ac2017-03-22 17:33:47 -070035#define IMAGE_FORMAT_UNKNOWN 0 // This is the same value as ImageFormat#UNKNOWN.
Zhijun Hef6a09e52015-02-24 18:12:23 -080036// ----------------------------------------------------------------------------
37
38using namespace android;
39
Zhijun Hef6a09e52015-02-24 18:12:23 -080040static struct {
41 jmethodID postEventFromNative;
42 jfieldID mWriterFormat;
43} gImageWriterClassInfo;
44
45static struct {
46 jfieldID mNativeBuffer;
47 jfieldID mNativeFenceFd;
48 jfieldID mPlanes;
49} gSurfaceImageClassInfo;
50
51static struct {
52 jclass clazz;
53 jmethodID ctor;
54} gSurfacePlaneClassInfo;
55
Zhijun Hef6a09e52015-02-24 18:12:23 -080056// ----------------------------------------------------------------------------
57
58class JNIImageWriterContext : public BnProducerListener {
59public:
60 JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz);
61
62 virtual ~JNIImageWriterContext();
63
64 // Implementation of IProducerListener, used to notify the ImageWriter that the consumer
65 // has returned a buffer and it is ready for ImageWriter to dequeue.
66 virtual void onBufferReleased();
67
Zhijun Hece9d6f92015-03-29 16:33:59 -070068 void setProducer(const sp<Surface>& producer) { mProducer = producer; }
69 Surface* getProducer() { return mProducer.get(); }
Zhijun Hef6a09e52015-02-24 18:12:23 -080070
71 void setBufferFormat(int format) { mFormat = format; }
72 int getBufferFormat() { return mFormat; }
73
74 void setBufferWidth(int width) { mWidth = width; }
75 int getBufferWidth() { return mWidth; }
76
77 void setBufferHeight(int height) { mHeight = height; }
78 int getBufferHeight() { return mHeight; }
79
80private:
81 static JNIEnv* getJNIEnv(bool* needsDetach);
82 static void detachJNI();
83
Zhijun Hece9d6f92015-03-29 16:33:59 -070084 sp<Surface> mProducer;
Zhijun Hef6a09e52015-02-24 18:12:23 -080085 jobject mWeakThiz;
86 jclass mClazz;
87 int mFormat;
88 int mWidth;
89 int mHeight;
90};
91
92JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
93 mWeakThiz(env->NewGlobalRef(weakThiz)),
94 mClazz((jclass)env->NewGlobalRef(clazz)),
95 mFormat(0),
96 mWidth(-1),
97 mHeight(-1) {
98}
99
100JNIImageWriterContext::~JNIImageWriterContext() {
101 ALOGV("%s", __FUNCTION__);
102 bool needsDetach = false;
103 JNIEnv* env = getJNIEnv(&needsDetach);
104 if (env != NULL) {
105 env->DeleteGlobalRef(mWeakThiz);
106 env->DeleteGlobalRef(mClazz);
107 } else {
108 ALOGW("leaking JNI object references");
109 }
110 if (needsDetach) {
111 detachJNI();
112 }
113
114 mProducer.clear();
115}
116
117JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
118 ALOGV("%s", __FUNCTION__);
119 LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
120 *needsDetach = false;
121 JNIEnv* env = AndroidRuntime::getJNIEnv();
122 if (env == NULL) {
123 JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
124 JavaVM* vm = AndroidRuntime::getJavaVM();
125 int result = vm->AttachCurrentThread(&env, (void*) &args);
126 if (result != JNI_OK) {
127 ALOGE("thread attach failed: %#x", result);
128 return NULL;
129 }
130 *needsDetach = true;
131 }
132 return env;
133}
134
135void JNIImageWriterContext::detachJNI() {
136 ALOGV("%s", __FUNCTION__);
137 JavaVM* vm = AndroidRuntime::getJavaVM();
138 int result = vm->DetachCurrentThread();
139 if (result != JNI_OK) {
140 ALOGE("thread detach failed: %#x", result);
141 }
142}
143
144void JNIImageWriterContext::onBufferReleased() {
145 ALOGV("%s: buffer released", __FUNCTION__);
146 bool needsDetach = false;
147 JNIEnv* env = getJNIEnv(&needsDetach);
148 if (env != NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700149 // Detach the buffer every time when a buffer consumption is done,
150 // need let this callback give a BufferItem, then only detach if it was attached to this
151 // Writer. Do the detach unconditionally for opaque format now. see b/19977520
152 if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
153 sp<Fence> fence;
Dan Stoza3316452f2015-04-27 11:31:12 -0700154 sp<GraphicBuffer> buffer;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700155 ALOGV("%s: One buffer is detached", __FUNCTION__);
156 mProducer->detachNextBuffer(&buffer, &fence);
157 }
158
Zhijun Hef6a09e52015-02-24 18:12:23 -0800159 env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
160 } else {
161 ALOGW("onBufferReleased event will not posted");
162 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700163
Zhijun Hef6a09e52015-02-24 18:12:23 -0800164 if (needsDetach) {
165 detachJNI();
166 }
167}
168
169// ----------------------------------------------------------------------------
170
171extern "C" {
172
173// -------------------------------Private method declarations--------------
174
Zhijun Hef6a09e52015-02-24 18:12:23 -0800175static void Image_setNativeContext(JNIEnv* env, jobject thiz,
176 sp<GraphicBuffer> buffer, int fenceFd);
177static void Image_getNativeContext(JNIEnv* env, jobject thiz,
178 GraphicBuffer** buffer, int* fenceFd);
179static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
180
181// --------------------------ImageWriter methods---------------------------------------
182
183static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
184 ALOGV("%s:", __FUNCTION__);
185 jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
186 LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
187 "can't find android/media/ImageWriter$WriterSurfaceImage");
188 gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
189 imageClazz, IMAGE_BUFFER_JNI_ID, "J");
190 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
191 "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
192
193 gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
194 imageClazz, "mNativeFenceFd", "I");
195 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
196 "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
197
198 gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
199 imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
200 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
201 "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
202
203 gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
204 clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
205 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
206 "can't find android/media/ImageWriter.postEventFromNative");
207
208 gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
209 clazz, "mWriterFormat", "I");
210 LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
211 "can't find android/media/ImageWriter.mWriterFormat");
212
213 jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
214 LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
215 // FindClass only gives a local reference of jclass object.
216 gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
217 gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
218 "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
219 LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
220 "Can not find SurfacePlane constructor");
221}
222
223static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
Zhijun He916d8ac2017-03-22 17:33:47 -0700224 jint maxImages, jint userFormat) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800225 status_t res;
226
227 ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
228
229 sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
230 if (surface == NULL) {
231 jniThrowException(env,
232 "java/lang/IllegalArgumentException",
233 "The surface has been released");
234 return 0;
235 }
236 sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
237
238 jclass clazz = env->GetObjectClass(thiz);
239 if (clazz == NULL) {
240 jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
241 return 0;
242 }
243 sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
244
245 sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
246 ctx->setProducer(producer);
247 /**
248 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
249 * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
250 * will be cleared after disconnect call.
251 */
252 producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
253 jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
254
255 // Get the dimension and format of the producer.
256 sp<ANativeWindow> anw = producer;
Zhijun He916d8ac2017-03-22 17:33:47 -0700257 int32_t width, height, surfaceFormat;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800258 if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
259 ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
260 jniThrowRuntimeException(env, "Failed to query Surface width");
261 return 0;
262 }
263 ctx->setBufferWidth(width);
264
265 if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
266 ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
267 jniThrowRuntimeException(env, "Failed to query Surface height");
268 return 0;
269 }
270 ctx->setBufferHeight(height);
271
Zhijun He916d8ac2017-03-22 17:33:47 -0700272 // Query surface format if no valid user format is specified, otherwise, override surface format
273 // with user format.
274 if (userFormat == IMAGE_FORMAT_UNKNOWN) {
275 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &surfaceFormat)) != OK) {
276 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
277 jniThrowRuntimeException(env, "Failed to query Surface format");
278 return 0;
279 }
280 } else {
281 surfaceFormat = userFormat;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800282 }
Zhijun He916d8ac2017-03-22 17:33:47 -0700283 ctx->setBufferFormat(surfaceFormat);
284 env->SetIntField(thiz,
285 gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(surfaceFormat));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800286
Zhijun He916d8ac2017-03-22 17:33:47 -0700287 if (!isFormatOpaque(surfaceFormat)) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800288 res = native_window_set_usage(anw.get(), GRALLOC_USAGE_SW_WRITE_OFTEN);
289 if (res != OK) {
290 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
Dan Albert1102e212015-06-09 17:35:38 -0700291 __FUNCTION__, static_cast<unsigned int>(GRALLOC_USAGE_SW_WRITE_OFTEN),
Zhijun He916d8ac2017-03-22 17:33:47 -0700292 surfaceFormat, strerror(-res), res);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800293 jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
294 return 0;
295 }
296 }
297
298 int minUndequeuedBufferCount = 0;
299 res = anw->query(anw.get(),
300 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
301 if (res != OK) {
302 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
303 __FUNCTION__, strerror(-res), res);
304 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
305 return 0;
306 }
307
308 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
309 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
310 if (res != OK) {
311 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
312 jniThrowRuntimeException(env, "Set buffer count failed");
313 return 0;
314 }
315
316 if (ctx != 0) {
317 ctx->incStrong((void*)ImageWriter_init);
318 }
319 return nativeCtx;
320}
321
322static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
323 ALOGV("%s", __FUNCTION__);
324 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
325 if (ctx == NULL || thiz == NULL) {
326 jniThrowException(env, "java/lang/IllegalStateException",
327 "ImageWriterContext is not initialized");
328 return;
329 }
330
331 sp<ANativeWindow> anw = ctx->getProducer();
332 android_native_buffer_t *anb = NULL;
333 int fenceFd = -1;
334 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
335 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700336 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700337 switch (res) {
338 case NO_INIT:
339 jniThrowException(env, "java/lang/IllegalStateException",
340 "Surface has been abandoned");
341 break;
342 default:
343 // TODO: handle other error cases here.
344 jniThrowRuntimeException(env, "dequeue buffer failed");
345 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800346 return;
347 }
348 // New GraphicBuffer object doesn't own the handle, thus the native buffer
349 // won't be freed when this object is destroyed.
Mathias Agopian845eef05f2017-04-03 17:51:15 -0700350 sp<GraphicBuffer> buffer(GraphicBuffer::from(anb));
Zhijun Hef6a09e52015-02-24 18:12:23 -0800351
352 // Note that:
353 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
354 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
355 // later.
356 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
357
358 // Finally, set the native info into image object.
359 Image_setNativeContext(env, image, buffer, fenceFd);
360}
361
362static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
363 ALOGV("%s:", __FUNCTION__);
364 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
365 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700366 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800367 return;
368 }
369
370 ANativeWindow* producer = ctx->getProducer();
371 if (producer != NULL) {
372 /**
373 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
374 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
375 * The producer listener will be cleared after disconnect call.
376 */
377 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
378 /**
379 * This is not an error. if client calling process dies, the window will
380 * also die and all calls to it will return DEAD_OBJECT, thus it's already
381 * "disconnected"
382 */
383 if (res == DEAD_OBJECT) {
384 ALOGW("%s: While disconnecting ImageWriter from native window, the"
385 " native window died already", __FUNCTION__);
386 } else if (res != OK) {
387 ALOGE("%s: native window disconnect failed: %s (%d)",
388 __FUNCTION__, strerror(-res), res);
389 jniThrowRuntimeException(env, "Native window disconnect failed");
390 return;
391 }
392 }
393
394 ctx->decStrong((void*)ImageWriter_init);
395}
396
397static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
398 ALOGV("%s", __FUNCTION__);
399 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
400 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800401 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800402 return;
403 }
404
405 sp<ANativeWindow> anw = ctx->getProducer();
406
407 GraphicBuffer *buffer = NULL;
408 int fenceFd = -1;
409 Image_getNativeContext(env, image, &buffer, &fenceFd);
410 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800411 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800412 return;
413 }
414
415 // Unlock the image if it was locked
416 Image_unlockIfLocked(env, image);
417
418 anw->cancelBuffer(anw.get(), buffer, fenceFd);
419
420 Image_setNativeContext(env, image, NULL, -1);
421}
422
423static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
Emilian Peev750aec62018-04-06 12:55:00 +0100424 jlong timestampNs, jint left, jint top, jint right, jint bottom, jint transform,
425 jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800426 ALOGV("%s", __FUNCTION__);
427 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
428 if (ctx == NULL || thiz == NULL) {
429 jniThrowException(env, "java/lang/IllegalStateException",
430 "ImageWriterContext is not initialized");
431 return;
432 }
433
434 status_t res = OK;
435 sp<ANativeWindow> anw = ctx->getProducer();
436
437 GraphicBuffer *buffer = NULL;
438 int fenceFd = -1;
439 Image_getNativeContext(env, image, &buffer, &fenceFd);
440 if (buffer == NULL) {
441 jniThrowException(env, "java/lang/IllegalStateException",
442 "Image is not initialized");
443 return;
444 }
445
446 // Unlock image if it was locked.
447 Image_unlockIfLocked(env, image);
448
449 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700450 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800451 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
452 if (res != OK) {
453 jniThrowRuntimeException(env, "Set timestamp failed");
454 return;
455 }
456
457 // Set crop
458 android_native_rect_t cropRect;
459 cropRect.left = left;
460 cropRect.top = top;
461 cropRect.right = right;
462 cropRect.bottom = bottom;
463 res = native_window_set_crop(anw.get(), &cropRect);
464 if (res != OK) {
465 jniThrowRuntimeException(env, "Set crop rect failed");
466 return;
467 }
468
Emilian Peev450a5ff2018-03-19 16:05:10 +0000469 res = native_window_set_buffers_transform(anw.get(), transform);
470 if (res != OK) {
471 jniThrowRuntimeException(env, "Set transform failed");
472 return;
473 }
474
Emilian Peev750aec62018-04-06 12:55:00 +0100475 res = native_window_set_scaling_mode(anw.get(), scalingMode);
476 if (res != OK) {
477 jniThrowRuntimeException(env, "Set scaling mode failed");
478 return;
479 }
480
Zhijun Hef6a09e52015-02-24 18:12:23 -0800481 // Finally, queue input buffer
482 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
483 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700484 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
485 switch (res) {
486 case NO_INIT:
487 jniThrowException(env, "java/lang/IllegalStateException",
488 "Surface has been abandoned");
489 break;
490 default:
491 // TODO: handle other error cases here.
492 jniThrowRuntimeException(env, "Queue input buffer failed");
493 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800494 return;
495 }
496
Zhijun Hece9d6f92015-03-29 16:33:59 -0700497 // Clear the image native context: end of this image's lifecycle in public API.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800498 Image_setNativeContext(env, image, NULL, -1);
499}
500
Zhijun Hece9d6f92015-03-29 16:33:59 -0700501static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
502 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint left, jint top,
Emilian Peev750aec62018-04-06 12:55:00 +0100503 jint right, jint bottom, jint transform, jint scalingMode) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800504 ALOGV("%s", __FUNCTION__);
505 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
506 if (ctx == NULL || thiz == NULL) {
507 jniThrowException(env, "java/lang/IllegalStateException",
508 "ImageWriterContext is not initialized");
Zhijun Hece9d6f92015-03-29 16:33:59 -0700509 return -1;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800510 }
511
Zhijun Hece9d6f92015-03-29 16:33:59 -0700512 sp<Surface> surface = ctx->getProducer();
513 status_t res = OK;
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700514 if (isFormatOpaque(imageFormat) != isFormatOpaque(ctx->getBufferFormat())) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800515 jniThrowException(env, "java/lang/IllegalStateException",
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700516 "Trying to attach an opaque image into a non-opaque ImageWriter, or vice versa");
Zhijun Hece9d6f92015-03-29 16:33:59 -0700517 return -1;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800518 }
519
Zhijun Hece9d6f92015-03-29 16:33:59 -0700520 // Image is guaranteed to be from ImageReader at this point, so it is safe to
521 // cast to BufferItem pointer.
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700522 BufferItem* buffer = reinterpret_cast<BufferItem*>(nativeBuffer);
523 if (buffer == NULL) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700524 jniThrowException(env, "java/lang/IllegalStateException",
525 "Image is not initialized or already closed");
526 return -1;
527 }
528
529 // Step 1. Attach Image
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700530 res = surface->attachBuffer(buffer->mGraphicBuffer.get());
Zhijun Hece9d6f92015-03-29 16:33:59 -0700531 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700532 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700533 switch (res) {
534 case NO_INIT:
535 jniThrowException(env, "java/lang/IllegalStateException",
536 "Surface has been abandoned");
537 break;
538 default:
539 // TODO: handle other error cases here.
540 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
541 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700542 return res;
543 }
544 sp < ANativeWindow > anw = surface;
545
Emilian Peev750aec62018-04-06 12:55:00 +0100546 // Step 2. Set timestamp, crop, transform and scaling mode. Note that we do not need unlock the
547 // image because it was not locked.
Zhijun Hece9d6f92015-03-29 16:33:59 -0700548 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
549 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
550 if (res != OK) {
551 jniThrowRuntimeException(env, "Set timestamp failed");
552 return res;
553 }
554
555 android_native_rect_t cropRect;
556 cropRect.left = left;
557 cropRect.top = top;
558 cropRect.right = right;
559 cropRect.bottom = bottom;
560 res = native_window_set_crop(anw.get(), &cropRect);
561 if (res != OK) {
562 jniThrowRuntimeException(env, "Set crop rect failed");
563 return res;
564 }
565
Emilian Peev450a5ff2018-03-19 16:05:10 +0000566 res = native_window_set_buffers_transform(anw.get(), transform);
567 if (res != OK) {
568 jniThrowRuntimeException(env, "Set transform failed");
569 return res;
570 }
571
Emilian Peev750aec62018-04-06 12:55:00 +0100572 res = native_window_set_scaling_mode(anw.get(), scalingMode);
573 if (res != OK) {
574 jniThrowRuntimeException(env, "Set scaling mode failed");
575 return res;
576 }
577
Zhijun Hece9d6f92015-03-29 16:33:59 -0700578 // Step 3. Queue Image.
Eino-Ville Talvala07ad4592017-05-02 12:44:05 -0700579 res = anw->queueBuffer(anw.get(), buffer->mGraphicBuffer.get(), /*fenceFd*/
Zhijun Hece9d6f92015-03-29 16:33:59 -0700580 -1);
581 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700582 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
583 switch (res) {
584 case NO_INIT:
585 jniThrowException(env, "java/lang/IllegalStateException",
586 "Surface has been abandoned");
587 break;
588 default:
589 // TODO: handle other error cases here.
590 jniThrowRuntimeException(env, "Queue input buffer failed");
591 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700592 return res;
593 }
594
595 // Do not set the image native context. Since it would overwrite the existing native context
596 // of the image that is from ImageReader, the subsequent image close will run into issues.
597
598 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800599}
600
601// --------------------------Image methods---------------------------------------
602
603static void Image_getNativeContext(JNIEnv* env, jobject thiz,
604 GraphicBuffer** buffer, int* fenceFd) {
605 ALOGV("%s", __FUNCTION__);
606 if (buffer != NULL) {
607 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
608 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
609 *buffer = gb;
610 }
611
612 if (fenceFd != NULL) {
613 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
614 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
615 }
616}
617
618static void Image_setNativeContext(JNIEnv* env, jobject thiz,
619 sp<GraphicBuffer> buffer, int fenceFd) {
620 ALOGV("%s:", __FUNCTION__);
621 GraphicBuffer* p = NULL;
622 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
623 if (buffer != 0) {
624 buffer->incStrong((void*)Image_setNativeContext);
625 }
626 if (p) {
627 p->decStrong((void*)Image_setNativeContext);
628 }
629 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
630 reinterpret_cast<jlong>(buffer.get()));
631
632 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
633}
634
635static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
636 ALOGV("%s", __FUNCTION__);
637 GraphicBuffer* buffer;
638 Image_getNativeContext(env, thiz, &buffer, NULL);
639 if (buffer == NULL) {
640 jniThrowException(env, "java/lang/IllegalStateException",
641 "Image is not initialized");
642 return;
643 }
644
645 // Is locked?
646 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700647 jobject planes = NULL;
648 if (!isFormatOpaque(buffer->getPixelFormat())) {
649 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
650 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800651 isLocked = (planes != NULL);
652 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700653 // 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 -0800654 status_t res = buffer->unlock();
655 if (res != OK) {
656 jniThrowRuntimeException(env, "unlock buffer failed");
657 }
658 ALOGV("Successfully unlocked the image");
659 }
660}
661
662static jint Image_getWidth(JNIEnv* env, jobject thiz) {
663 ALOGV("%s", __FUNCTION__);
664 GraphicBuffer* buffer;
665 Image_getNativeContext(env, thiz, &buffer, NULL);
666 if (buffer == NULL) {
667 jniThrowException(env, "java/lang/IllegalStateException",
668 "Image is not initialized");
669 return -1;
670 }
671
672 return buffer->getWidth();
673}
674
675static jint Image_getHeight(JNIEnv* env, jobject thiz) {
676 ALOGV("%s", __FUNCTION__);
677 GraphicBuffer* buffer;
678 Image_getNativeContext(env, thiz, &buffer, NULL);
679 if (buffer == NULL) {
680 jniThrowException(env, "java/lang/IllegalStateException",
681 "Image is not initialized");
682 return -1;
683 }
684
685 return buffer->getHeight();
686}
687
Zhijun Hef6a09e52015-02-24 18:12:23 -0800688static jint Image_getFormat(JNIEnv* env, jobject thiz) {
689 ALOGV("%s", __FUNCTION__);
690 GraphicBuffer* buffer;
691 Image_getNativeContext(env, thiz, &buffer, NULL);
692 if (buffer == NULL) {
693 jniThrowException(env, "java/lang/IllegalStateException",
694 "Image is not initialized");
695 return 0;
696 }
697
Zhijun He0ab41622016-02-25 16:00:38 -0800698 // ImageWriter doesn't support data space yet, assuming it is unknown.
699 PublicFormat publicFmt = android_view_Surface_mapHalFormatDataspaceToPublicFormat(
700 buffer->getPixelFormat(), HAL_DATASPACE_UNKNOWN);
701 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800702}
703
704static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
705 ALOGV("%s:", __FUNCTION__);
706 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
707}
708
709static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
710 ALOGV("%s", __FUNCTION__);
711 GraphicBuffer* buffer;
712 int fenceFd = -1;
713 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
714 if (buffer == NULL) {
715 jniThrowException(env, "java/lang/IllegalStateException",
716 "Image is not initialized");
717 return;
718 }
719
Zhijun He0ab41622016-02-25 16:00:38 -0800720 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
721 const Rect noCrop(buffer->width, buffer->height);
722 status_t res = lockImageFromBuffer(
723 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
724 // Clear the fenceFd as it is already consumed by lock call.
725 Image_setFenceFd(env, thiz, /*fenceFd*/-1);
726 if (res != OK) {
727 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
728 "lock buffer failed for format 0x%x",
729 buffer->getPixelFormat());
730 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800731 }
732
Zhijun He0ab41622016-02-25 16:00:38 -0800733 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800734 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
735 // and we don't set them here.
736}
737
Zhijun Hef6a09e52015-02-24 18:12:23 -0800738static void Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
739 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
740 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800741
Zhijun He0ab41622016-02-25 16:00:38 -0800742 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
743 pixelStride, rowStride);
744 if (res != OK) {
745 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
746 "Pixel format: 0x%x is unsupported", buffer->flexFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800747 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800748}
749
750static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
751 int numPlanes, int writerFormat) {
752 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
753 int rowStride, pixelStride;
754 uint8_t *pData;
755 uint32_t dataSize;
756 jobject byteBuffer;
757
758 int format = Image_getFormat(env, thiz);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700759 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800760 String8 msg;
761 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
762 " must be 0", format, numPlanes);
763 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
764 return NULL;
765 }
766
767 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
768 /*initial_element*/NULL);
769 if (surfacePlanes == NULL) {
770 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
771 " probably out of memory");
772 return NULL;
773 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700774 if (isFormatOpaque(format)) {
775 return surfacePlanes;
776 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800777
778 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
779 LockedImage lockedImg = LockedImage();
780 Image_getLockedImage(env, thiz, &lockedImg);
781
782 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -0800783 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
784 writerFormat = android_view_Surface_mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800785 for (int i = 0; i < numPlanes; i++) {
786 Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
787 &pData, &dataSize, &pixelStride, &rowStride);
788 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
789 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
790 jniThrowException(env, "java/lang/IllegalStateException",
791 "Failed to allocate ByteBuffer");
792 return NULL;
793 }
794
795 // Finally, create this SurfacePlane.
796 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
797 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
798 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
799 }
800
801 return surfacePlanes;
802}
803
Zhijun Hef6a09e52015-02-24 18:12:23 -0800804} // extern "C"
805
806// ----------------------------------------------------------------------------
807
808static JNINativeMethod gImageWriterMethods[] = {
809 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
Zhijun He916d8ac2017-03-22 17:33:47 -0700810 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;II)J",
Zhijun Hef6a09e52015-02-24 18:12:23 -0800811 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -0700812 {"nativeClose", "(J)V", (void*)ImageWriter_close },
Emilian Peev750aec62018-04-06 12:55:00 +0100813 {"nativeAttachAndQueueImage", "(JJIJIIIIII)I", (void*)ImageWriter_attachAndQueueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -0800814 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
Emilian Peev750aec62018-04-06 12:55:00 +0100815 {"nativeQueueInputImage", "(JLandroid/media/Image;JIIIIII)V", (void*)ImageWriter_queueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -0800816 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
817};
818
819static JNINativeMethod gImageMethods[] = {
820 {"nativeCreatePlanes", "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
821 (void*)Image_createSurfacePlanes },
822 {"nativeGetWidth", "()I", (void*)Image_getWidth },
823 {"nativeGetHeight", "()I", (void*)Image_getHeight },
824 {"nativeGetFormat", "()I", (void*)Image_getFormat },
825};
826
827int register_android_media_ImageWriter(JNIEnv *env) {
828
829 int ret1 = AndroidRuntime::registerNativeMethods(env,
830 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
831
832 int ret2 = AndroidRuntime::registerNativeMethods(env,
833 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
834
835 return (ret1 || ret2);
836}