blob: 1cfb3cfd34cd318c27656773e78d1b9ecf9104cf [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"
35
36// ----------------------------------------------------------------------------
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,
224 jint maxImages) {
225 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;
257 int32_t width, height, format;
258 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
272 if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &format)) != OK) {
273 ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
274 jniThrowRuntimeException(env, "Failed to query Surface format");
275 return 0;
276 }
277 ctx->setBufferFormat(format);
278 env->SetIntField(thiz, gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(format));
279
280
Zhijun Hece9d6f92015-03-29 16:33:59 -0700281 if (!isFormatOpaque(format)) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800282 res = native_window_set_usage(anw.get(), GRALLOC_USAGE_SW_WRITE_OFTEN);
283 if (res != OK) {
284 ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
Dan Albert1102e212015-06-09 17:35:38 -0700285 __FUNCTION__, static_cast<unsigned int>(GRALLOC_USAGE_SW_WRITE_OFTEN),
286 format, strerror(-res), res);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800287 jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
288 return 0;
289 }
290 }
291
292 int minUndequeuedBufferCount = 0;
293 res = anw->query(anw.get(),
294 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
295 if (res != OK) {
296 ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
297 __FUNCTION__, strerror(-res), res);
298 jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
299 return 0;
300 }
301
302 size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
303 res = native_window_set_buffer_count(anw.get(), totalBufferCount);
304 if (res != OK) {
305 ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
306 jniThrowRuntimeException(env, "Set buffer count failed");
307 return 0;
308 }
309
310 if (ctx != 0) {
311 ctx->incStrong((void*)ImageWriter_init);
312 }
313 return nativeCtx;
314}
315
316static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
317 ALOGV("%s", __FUNCTION__);
318 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
319 if (ctx == NULL || thiz == NULL) {
320 jniThrowException(env, "java/lang/IllegalStateException",
321 "ImageWriterContext is not initialized");
322 return;
323 }
324
325 sp<ANativeWindow> anw = ctx->getProducer();
326 android_native_buffer_t *anb = NULL;
327 int fenceFd = -1;
328 status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
329 if (res != OK) {
Zhijun Hea5827142015-04-22 10:07:42 -0700330 ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700331 switch (res) {
332 case NO_INIT:
333 jniThrowException(env, "java/lang/IllegalStateException",
334 "Surface has been abandoned");
335 break;
336 default:
337 // TODO: handle other error cases here.
338 jniThrowRuntimeException(env, "dequeue buffer failed");
339 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800340 return;
341 }
342 // New GraphicBuffer object doesn't own the handle, thus the native buffer
343 // won't be freed when this object is destroyed.
344 sp<GraphicBuffer> buffer(new GraphicBuffer(anb, /*keepOwnership*/false));
345
346 // Note that:
347 // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
348 // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
349 // later.
350 // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
351
352 // Finally, set the native info into image object.
353 Image_setNativeContext(env, image, buffer, fenceFd);
354}
355
356static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
357 ALOGV("%s:", __FUNCTION__);
358 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
359 if (ctx == NULL || thiz == NULL) {
Chien-Yu Chen0375cb02015-06-18 11:55:18 -0700360 // ImageWriter is already closed.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800361 return;
362 }
363
364 ANativeWindow* producer = ctx->getProducer();
365 if (producer != NULL) {
366 /**
367 * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
368 * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
369 * The producer listener will be cleared after disconnect call.
370 */
371 status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
372 /**
373 * This is not an error. if client calling process dies, the window will
374 * also die and all calls to it will return DEAD_OBJECT, thus it's already
375 * "disconnected"
376 */
377 if (res == DEAD_OBJECT) {
378 ALOGW("%s: While disconnecting ImageWriter from native window, the"
379 " native window died already", __FUNCTION__);
380 } else if (res != OK) {
381 ALOGE("%s: native window disconnect failed: %s (%d)",
382 __FUNCTION__, strerror(-res), res);
383 jniThrowRuntimeException(env, "Native window disconnect failed");
384 return;
385 }
386 }
387
388 ctx->decStrong((void*)ImageWriter_init);
389}
390
391static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
392 ALOGV("%s", __FUNCTION__);
393 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
394 if (ctx == NULL || thiz == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800395 ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
Zhijun Hef6a09e52015-02-24 18:12:23 -0800396 return;
397 }
398
399 sp<ANativeWindow> anw = ctx->getProducer();
400
401 GraphicBuffer *buffer = NULL;
402 int fenceFd = -1;
403 Image_getNativeContext(env, image, &buffer, &fenceFd);
404 if (buffer == NULL) {
Zhijun Hedc6bb242015-12-03 15:34:34 -0800405 // Cancel an already cancelled image is harmless.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800406 return;
407 }
408
409 // Unlock the image if it was locked
410 Image_unlockIfLocked(env, image);
411
412 anw->cancelBuffer(anw.get(), buffer, fenceFd);
413
414 Image_setNativeContext(env, image, NULL, -1);
415}
416
417static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
418 jlong timestampNs, jint left, jint top, jint right, jint bottom) {
419 ALOGV("%s", __FUNCTION__);
420 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
421 if (ctx == NULL || thiz == NULL) {
422 jniThrowException(env, "java/lang/IllegalStateException",
423 "ImageWriterContext is not initialized");
424 return;
425 }
426
427 status_t res = OK;
428 sp<ANativeWindow> anw = ctx->getProducer();
429
430 GraphicBuffer *buffer = NULL;
431 int fenceFd = -1;
432 Image_getNativeContext(env, image, &buffer, &fenceFd);
433 if (buffer == NULL) {
434 jniThrowException(env, "java/lang/IllegalStateException",
435 "Image is not initialized");
436 return;
437 }
438
439 // Unlock image if it was locked.
440 Image_unlockIfLocked(env, image);
441
442 // Set timestamp
Zhijun Hed1cbc682015-03-23 10:10:04 -0700443 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800444 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
445 if (res != OK) {
446 jniThrowRuntimeException(env, "Set timestamp failed");
447 return;
448 }
449
450 // Set crop
451 android_native_rect_t cropRect;
452 cropRect.left = left;
453 cropRect.top = top;
454 cropRect.right = right;
455 cropRect.bottom = bottom;
456 res = native_window_set_crop(anw.get(), &cropRect);
457 if (res != OK) {
458 jniThrowRuntimeException(env, "Set crop rect failed");
459 return;
460 }
461
462 // Finally, queue input buffer
463 res = anw->queueBuffer(anw.get(), buffer, fenceFd);
464 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700465 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
466 switch (res) {
467 case NO_INIT:
468 jniThrowException(env, "java/lang/IllegalStateException",
469 "Surface has been abandoned");
470 break;
471 default:
472 // TODO: handle other error cases here.
473 jniThrowRuntimeException(env, "Queue input buffer failed");
474 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800475 return;
476 }
477
Zhijun Hece9d6f92015-03-29 16:33:59 -0700478 // Clear the image native context: end of this image's lifecycle in public API.
Zhijun Hef6a09e52015-02-24 18:12:23 -0800479 Image_setNativeContext(env, image, NULL, -1);
480}
481
Zhijun Hece9d6f92015-03-29 16:33:59 -0700482static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
483 jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint left, jint top,
484 jint right, jint bottom) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800485 ALOGV("%s", __FUNCTION__);
486 JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
487 if (ctx == NULL || thiz == NULL) {
488 jniThrowException(env, "java/lang/IllegalStateException",
489 "ImageWriterContext is not initialized");
Zhijun Hece9d6f92015-03-29 16:33:59 -0700490 return -1;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800491 }
492
Zhijun Hece9d6f92015-03-29 16:33:59 -0700493 sp<Surface> surface = ctx->getProducer();
494 status_t res = OK;
495 if (!isFormatOpaque(imageFormat)) {
496 // TODO: need implement, see b/19962027
497 jniThrowRuntimeException(env,
498 "nativeAttachImage for non-opaque image is not implement yet!!!");
499 return -1;
500 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800501
Zhijun Hece9d6f92015-03-29 16:33:59 -0700502 if (!isFormatOpaque(ctx->getBufferFormat())) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800503 jniThrowException(env, "java/lang/IllegalStateException",
Zhijun Hece9d6f92015-03-29 16:33:59 -0700504 "Trying to attach an opaque image into a non-opaque ImageWriter");
505 return -1;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800506 }
507
Zhijun Hece9d6f92015-03-29 16:33:59 -0700508 // Image is guaranteed to be from ImageReader at this point, so it is safe to
509 // cast to BufferItem pointer.
510 BufferItem* opaqueBuffer = reinterpret_cast<BufferItem*>(nativeBuffer);
511 if (opaqueBuffer == NULL) {
512 jniThrowException(env, "java/lang/IllegalStateException",
513 "Image is not initialized or already closed");
514 return -1;
515 }
516
517 // Step 1. Attach Image
518 res = surface->attachBuffer(opaqueBuffer->mGraphicBuffer.get());
519 if (res != OK) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700520 ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700521 switch (res) {
522 case NO_INIT:
523 jniThrowException(env, "java/lang/IllegalStateException",
524 "Surface has been abandoned");
525 break;
526 default:
527 // TODO: handle other error cases here.
528 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
529 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700530 return res;
531 }
532 sp < ANativeWindow > anw = surface;
533
534 // Step 2. Set timestamp and crop. Note that we do not need unlock the image because
535 // it was not locked.
536 ALOGV("timestamp to be queued: %" PRId64, timestampNs);
537 res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
538 if (res != OK) {
539 jniThrowRuntimeException(env, "Set timestamp failed");
540 return res;
541 }
542
543 android_native_rect_t cropRect;
544 cropRect.left = left;
545 cropRect.top = top;
546 cropRect.right = right;
547 cropRect.bottom = bottom;
548 res = native_window_set_crop(anw.get(), &cropRect);
549 if (res != OK) {
550 jniThrowRuntimeException(env, "Set crop rect failed");
551 return res;
552 }
553
554 // Step 3. Queue Image.
555 res = anw->queueBuffer(anw.get(), opaqueBuffer->mGraphicBuffer.get(), /*fenceFd*/
556 -1);
557 if (res != OK) {
Chien-Yu Chene0ee6302015-07-06 17:46:05 -0700558 ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
559 switch (res) {
560 case NO_INIT:
561 jniThrowException(env, "java/lang/IllegalStateException",
562 "Surface has been abandoned");
563 break;
564 default:
565 // TODO: handle other error cases here.
566 jniThrowRuntimeException(env, "Queue input buffer failed");
567 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700568 return res;
569 }
570
571 // Do not set the image native context. Since it would overwrite the existing native context
572 // of the image that is from ImageReader, the subsequent image close will run into issues.
573
574 return res;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800575}
576
577// --------------------------Image methods---------------------------------------
578
579static void Image_getNativeContext(JNIEnv* env, jobject thiz,
580 GraphicBuffer** buffer, int* fenceFd) {
581 ALOGV("%s", __FUNCTION__);
582 if (buffer != NULL) {
583 GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
584 (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
585 *buffer = gb;
586 }
587
588 if (fenceFd != NULL) {
589 *fenceFd = reinterpret_cast<jint>(env->GetIntField(
590 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
591 }
592}
593
594static void Image_setNativeContext(JNIEnv* env, jobject thiz,
595 sp<GraphicBuffer> buffer, int fenceFd) {
596 ALOGV("%s:", __FUNCTION__);
597 GraphicBuffer* p = NULL;
598 Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
599 if (buffer != 0) {
600 buffer->incStrong((void*)Image_setNativeContext);
601 }
602 if (p) {
603 p->decStrong((void*)Image_setNativeContext);
604 }
605 env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
606 reinterpret_cast<jlong>(buffer.get()));
607
608 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
609}
610
611static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
612 ALOGV("%s", __FUNCTION__);
613 GraphicBuffer* buffer;
614 Image_getNativeContext(env, thiz, &buffer, NULL);
615 if (buffer == NULL) {
616 jniThrowException(env, "java/lang/IllegalStateException",
617 "Image is not initialized");
618 return;
619 }
620
621 // Is locked?
622 bool isLocked = false;
Zhijun Hece9d6f92015-03-29 16:33:59 -0700623 jobject planes = NULL;
624 if (!isFormatOpaque(buffer->getPixelFormat())) {
625 planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
626 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800627 isLocked = (planes != NULL);
628 if (isLocked) {
Zhijun Hece9d6f92015-03-29 16:33:59 -0700629 // 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 -0800630 status_t res = buffer->unlock();
631 if (res != OK) {
632 jniThrowRuntimeException(env, "unlock buffer failed");
633 }
634 ALOGV("Successfully unlocked the image");
635 }
636}
637
638static jint Image_getWidth(JNIEnv* env, jobject thiz) {
639 ALOGV("%s", __FUNCTION__);
640 GraphicBuffer* buffer;
641 Image_getNativeContext(env, thiz, &buffer, NULL);
642 if (buffer == NULL) {
643 jniThrowException(env, "java/lang/IllegalStateException",
644 "Image is not initialized");
645 return -1;
646 }
647
648 return buffer->getWidth();
649}
650
651static jint Image_getHeight(JNIEnv* env, jobject thiz) {
652 ALOGV("%s", __FUNCTION__);
653 GraphicBuffer* buffer;
654 Image_getNativeContext(env, thiz, &buffer, NULL);
655 if (buffer == NULL) {
656 jniThrowException(env, "java/lang/IllegalStateException",
657 "Image is not initialized");
658 return -1;
659 }
660
661 return buffer->getHeight();
662}
663
Zhijun Hef6a09e52015-02-24 18:12:23 -0800664static jint Image_getFormat(JNIEnv* env, jobject thiz) {
665 ALOGV("%s", __FUNCTION__);
666 GraphicBuffer* buffer;
667 Image_getNativeContext(env, thiz, &buffer, NULL);
668 if (buffer == NULL) {
669 jniThrowException(env, "java/lang/IllegalStateException",
670 "Image is not initialized");
671 return 0;
672 }
673
Zhijun He0ab41622016-02-25 16:00:38 -0800674 // ImageWriter doesn't support data space yet, assuming it is unknown.
675 PublicFormat publicFmt = android_view_Surface_mapHalFormatDataspaceToPublicFormat(
676 buffer->getPixelFormat(), HAL_DATASPACE_UNKNOWN);
677 return static_cast<jint>(publicFmt);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800678}
679
680static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
681 ALOGV("%s:", __FUNCTION__);
682 env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
683}
684
685static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
686 ALOGV("%s", __FUNCTION__);
687 GraphicBuffer* buffer;
688 int fenceFd = -1;
689 Image_getNativeContext(env, thiz, &buffer, &fenceFd);
690 if (buffer == NULL) {
691 jniThrowException(env, "java/lang/IllegalStateException",
692 "Image is not initialized");
693 return;
694 }
695
Zhijun He0ab41622016-02-25 16:00:38 -0800696 // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
697 const Rect noCrop(buffer->width, buffer->height);
698 status_t res = lockImageFromBuffer(
699 buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
700 // Clear the fenceFd as it is already consumed by lock call.
701 Image_setFenceFd(env, thiz, /*fenceFd*/-1);
702 if (res != OK) {
703 jniThrowExceptionFmt(env, "java/lang/RuntimeException",
704 "lock buffer failed for format 0x%x",
705 buffer->getPixelFormat());
706 return;
Zhijun Hef6a09e52015-02-24 18:12:23 -0800707 }
708
Zhijun He0ab41622016-02-25 16:00:38 -0800709 ALOGV("%s: Successfully locked the image", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800710 // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
711 // and we don't set them here.
712}
713
Zhijun Hef6a09e52015-02-24 18:12:23 -0800714static void Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
715 int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
716 ALOGV("%s", __FUNCTION__);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800717
Zhijun He0ab41622016-02-25 16:00:38 -0800718 status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
719 pixelStride, rowStride);
720 if (res != OK) {
721 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
722 "Pixel format: 0x%x is unsupported", buffer->flexFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800723 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800724}
725
726static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
727 int numPlanes, int writerFormat) {
728 ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
729 int rowStride, pixelStride;
730 uint8_t *pData;
731 uint32_t dataSize;
732 jobject byteBuffer;
733
734 int format = Image_getFormat(env, thiz);
Zhijun Hece9d6f92015-03-29 16:33:59 -0700735 if (isFormatOpaque(format) && numPlanes > 0) {
Zhijun Hef6a09e52015-02-24 18:12:23 -0800736 String8 msg;
737 msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
738 " must be 0", format, numPlanes);
739 jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
740 return NULL;
741 }
742
743 jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
744 /*initial_element*/NULL);
745 if (surfacePlanes == NULL) {
746 jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
747 " probably out of memory");
748 return NULL;
749 }
Zhijun Hece9d6f92015-03-29 16:33:59 -0700750 if (isFormatOpaque(format)) {
751 return surfacePlanes;
752 }
Zhijun Hef6a09e52015-02-24 18:12:23 -0800753
754 // Buildup buffer info: rowStride, pixelStride and byteBuffers.
755 LockedImage lockedImg = LockedImage();
756 Image_getLockedImage(env, thiz, &lockedImg);
757
758 // Create all SurfacePlanes
Zhijun He0ab41622016-02-25 16:00:38 -0800759 PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
760 writerFormat = android_view_Surface_mapPublicFormatToHalFormat(publicWriterFormat);
Zhijun Hef6a09e52015-02-24 18:12:23 -0800761 for (int i = 0; i < numPlanes; i++) {
762 Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
763 &pData, &dataSize, &pixelStride, &rowStride);
764 byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
765 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
766 jniThrowException(env, "java/lang/IllegalStateException",
767 "Failed to allocate ByteBuffer");
768 return NULL;
769 }
770
771 // Finally, create this SurfacePlane.
772 jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
773 gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
774 env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
775 }
776
777 return surfacePlanes;
778}
779
Zhijun Hef6a09e52015-02-24 18:12:23 -0800780} // extern "C"
781
782// ----------------------------------------------------------------------------
783
784static JNINativeMethod gImageWriterMethods[] = {
785 {"nativeClassInit", "()V", (void*)ImageWriter_classInit },
786 {"nativeInit", "(Ljava/lang/Object;Landroid/view/Surface;I)J",
787 (void*)ImageWriter_init },
Zhijun Hece9d6f92015-03-29 16:33:59 -0700788 {"nativeClose", "(J)V", (void*)ImageWriter_close },
789 {"nativeAttachAndQueueImage", "(JJIJIIII)I", (void*)ImageWriter_attachAndQueueImage },
Zhijun Hef6a09e52015-02-24 18:12:23 -0800790 {"nativeDequeueInputImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_dequeueImage },
791 {"nativeQueueInputImage", "(JLandroid/media/Image;JIIII)V", (void*)ImageWriter_queueImage },
792 {"cancelImage", "(JLandroid/media/Image;)V", (void*)ImageWriter_cancelImage },
793};
794
795static JNINativeMethod gImageMethods[] = {
796 {"nativeCreatePlanes", "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
797 (void*)Image_createSurfacePlanes },
798 {"nativeGetWidth", "()I", (void*)Image_getWidth },
799 {"nativeGetHeight", "()I", (void*)Image_getHeight },
800 {"nativeGetFormat", "()I", (void*)Image_getFormat },
801};
802
803int register_android_media_ImageWriter(JNIEnv *env) {
804
805 int ret1 = AndroidRuntime::registerNativeMethods(env,
806 "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
807
808 int ret2 = AndroidRuntime::registerNativeMethods(env,
809 "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
810
811 return (ret1 || ret2);
812}
813