• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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"
19 #include "android_media_Utils.h"
20 
21 #include <utils/Log.h>
22 #include <utils/String8.h>
23 
24 #include <gui/IProducerListener.h>
25 #include <gui/Surface.h>
26 #include <android_runtime/AndroidRuntime.h>
27 #include <android_runtime/android_view_Surface.h>
28 #include <camera3.h>
29 #include <jni.h>
30 #include <JNIHelp.h>
31 
32 #include <stdint.h>
33 #include <inttypes.h>
34 
35 #define IMAGE_BUFFER_JNI_ID           "mNativeBuffer"
36 
37 // ----------------------------------------------------------------------------
38 
39 using namespace android;
40 
41 static struct {
42     jmethodID postEventFromNative;
43     jfieldID mWriterFormat;
44 } gImageWriterClassInfo;
45 
46 static struct {
47     jfieldID mNativeBuffer;
48     jfieldID mNativeFenceFd;
49     jfieldID mPlanes;
50 } gSurfaceImageClassInfo;
51 
52 static struct {
53     jclass clazz;
54     jmethodID ctor;
55 } gSurfacePlaneClassInfo;
56 
57 // ----------------------------------------------------------------------------
58 
59 class JNIImageWriterContext : public BnProducerListener {
60 public:
61     JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz);
62 
63     virtual ~JNIImageWriterContext();
64 
65     // Implementation of IProducerListener, used to notify the ImageWriter that the consumer
66     // has returned a buffer and it is ready for ImageWriter to dequeue.
67     virtual void onBufferReleased();
68 
setProducer(const sp<Surface> & producer)69     void setProducer(const sp<Surface>& producer) { mProducer = producer; }
getProducer()70     Surface* getProducer() { return mProducer.get(); }
71 
setBufferFormat(int format)72     void setBufferFormat(int format) { mFormat = format; }
getBufferFormat()73     int getBufferFormat() { return mFormat; }
74 
setBufferWidth(int width)75     void setBufferWidth(int width) { mWidth = width; }
getBufferWidth()76     int getBufferWidth() { return mWidth; }
77 
setBufferHeight(int height)78     void setBufferHeight(int height) { mHeight = height; }
getBufferHeight()79     int getBufferHeight() { return mHeight; }
80 
81 private:
82     static JNIEnv* getJNIEnv(bool* needsDetach);
83     static void detachJNI();
84 
85     sp<Surface> mProducer;
86     jobject mWeakThiz;
87     jclass mClazz;
88     int mFormat;
89     int mWidth;
90     int mHeight;
91 };
92 
JNIImageWriterContext(JNIEnv * env,jobject weakThiz,jclass clazz)93 JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
94     mWeakThiz(env->NewGlobalRef(weakThiz)),
95     mClazz((jclass)env->NewGlobalRef(clazz)),
96     mFormat(0),
97     mWidth(-1),
98     mHeight(-1) {
99 }
100 
~JNIImageWriterContext()101 JNIImageWriterContext::~JNIImageWriterContext() {
102     ALOGV("%s", __FUNCTION__);
103     bool needsDetach = false;
104     JNIEnv* env = getJNIEnv(&needsDetach);
105     if (env != NULL) {
106         env->DeleteGlobalRef(mWeakThiz);
107         env->DeleteGlobalRef(mClazz);
108     } else {
109         ALOGW("leaking JNI object references");
110     }
111     if (needsDetach) {
112         detachJNI();
113     }
114 
115     mProducer.clear();
116 }
117 
getJNIEnv(bool * needsDetach)118 JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
119     ALOGV("%s", __FUNCTION__);
120     LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
121     *needsDetach = false;
122     JNIEnv* env = AndroidRuntime::getJNIEnv();
123     if (env == NULL) {
124         JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
125         JavaVM* vm = AndroidRuntime::getJavaVM();
126         int result = vm->AttachCurrentThread(&env, (void*) &args);
127         if (result != JNI_OK) {
128             ALOGE("thread attach failed: %#x", result);
129             return NULL;
130         }
131         *needsDetach = true;
132     }
133     return env;
134 }
135 
detachJNI()136 void JNIImageWriterContext::detachJNI() {
137     ALOGV("%s", __FUNCTION__);
138     JavaVM* vm = AndroidRuntime::getJavaVM();
139     int result = vm->DetachCurrentThread();
140     if (result != JNI_OK) {
141         ALOGE("thread detach failed: %#x", result);
142     }
143 }
144 
onBufferReleased()145 void JNIImageWriterContext::onBufferReleased() {
146     ALOGV("%s: buffer released", __FUNCTION__);
147     bool needsDetach = false;
148     JNIEnv* env = getJNIEnv(&needsDetach);
149     if (env != NULL) {
150         // Detach the buffer every time when a buffer consumption is done,
151         // need let this callback give a BufferItem, then only detach if it was attached to this
152         // Writer. Do the detach unconditionally for opaque format now. see b/19977520
153         if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
154             sp<Fence> fence;
155             sp<GraphicBuffer> buffer;
156             ALOGV("%s: One buffer is detached", __FUNCTION__);
157             mProducer->detachNextBuffer(&buffer, &fence);
158         }
159 
160         env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
161     } else {
162         ALOGW("onBufferReleased event will not posted");
163     }
164 
165     if (needsDetach) {
166         detachJNI();
167     }
168 }
169 
170 // ----------------------------------------------------------------------------
171 
172 extern "C" {
173 
174 // -------------------------------Private method declarations--------------
175 
176 static void Image_setNativeContext(JNIEnv* env, jobject thiz,
177         sp<GraphicBuffer> buffer, int fenceFd);
178 static void Image_getNativeContext(JNIEnv* env, jobject thiz,
179         GraphicBuffer** buffer, int* fenceFd);
180 static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
181 
182 // --------------------------ImageWriter methods---------------------------------------
183 
ImageWriter_classInit(JNIEnv * env,jclass clazz)184 static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
185     ALOGV("%s:", __FUNCTION__);
186     jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
187     LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
188             "can't find android/media/ImageWriter$WriterSurfaceImage");
189     gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
190             imageClazz, IMAGE_BUFFER_JNI_ID, "J");
191     LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
192             "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
193 
194     gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
195             imageClazz, "mNativeFenceFd", "I");
196     LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
197             "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
198 
199     gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
200             imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
201     LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
202             "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
203 
204     gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
205             clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
206     LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
207                         "can't find android/media/ImageWriter.postEventFromNative");
208 
209     gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
210             clazz, "mWriterFormat", "I");
211     LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
212                         "can't find android/media/ImageWriter.mWriterFormat");
213 
214     jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
215     LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
216     // FindClass only gives a local reference of jclass object.
217     gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
218     gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
219             "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
220     LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
221             "Can not find SurfacePlane constructor");
222 }
223 
ImageWriter_init(JNIEnv * env,jobject thiz,jobject weakThiz,jobject jsurface,jint maxImages)224 static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
225         jint maxImages) {
226     status_t res;
227 
228     ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
229 
230     sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
231     if (surface == NULL) {
232         jniThrowException(env,
233                 "java/lang/IllegalArgumentException",
234                 "The surface has been released");
235         return 0;
236      }
237     sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
238 
239     jclass clazz = env->GetObjectClass(thiz);
240     if (clazz == NULL) {
241         jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
242         return 0;
243     }
244     sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
245 
246     sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
247     ctx->setProducer(producer);
248     /**
249      * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
250      * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
251      * will be cleared after disconnect call.
252      */
253     producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
254     jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
255 
256     // Get the dimension and format of the producer.
257     sp<ANativeWindow> anw = producer;
258     int32_t width, height, format;
259     if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
260         ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
261         jniThrowRuntimeException(env, "Failed to query Surface width");
262         return 0;
263     }
264     ctx->setBufferWidth(width);
265 
266     if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
267         ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
268         jniThrowRuntimeException(env, "Failed to query Surface height");
269         return 0;
270     }
271     ctx->setBufferHeight(height);
272 
273     if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &format)) != OK) {
274         ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
275         jniThrowRuntimeException(env, "Failed to query Surface format");
276         return 0;
277     }
278     ctx->setBufferFormat(format);
279     env->SetIntField(thiz, gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(format));
280 
281 
282     if (!isFormatOpaque(format)) {
283         res = native_window_set_usage(anw.get(), GRALLOC_USAGE_SW_WRITE_OFTEN);
284         if (res != OK) {
285             ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
286                   __FUNCTION__, static_cast<unsigned int>(GRALLOC_USAGE_SW_WRITE_OFTEN),
287                   format, strerror(-res), res);
288             jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
289             return 0;
290         }
291     }
292 
293     int minUndequeuedBufferCount = 0;
294     res = anw->query(anw.get(),
295                 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
296     if (res != OK) {
297         ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
298                 __FUNCTION__, strerror(-res), res);
299         jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
300         return 0;
301      }
302 
303     size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
304     res = native_window_set_buffer_count(anw.get(), totalBufferCount);
305     if (res != OK) {
306         ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
307         jniThrowRuntimeException(env, "Set buffer count failed");
308         return 0;
309     }
310 
311     if (ctx != 0) {
312         ctx->incStrong((void*)ImageWriter_init);
313     }
314     return nativeCtx;
315 }
316 
ImageWriter_dequeueImage(JNIEnv * env,jobject thiz,jlong nativeCtx,jobject image)317 static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
318     ALOGV("%s", __FUNCTION__);
319     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
320     if (ctx == NULL || thiz == NULL) {
321         jniThrowException(env, "java/lang/IllegalStateException",
322                 "ImageWriterContext is not initialized");
323         return;
324     }
325 
326     sp<ANativeWindow> anw = ctx->getProducer();
327     android_native_buffer_t *anb = NULL;
328     int fenceFd = -1;
329     status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
330     if (res != OK) {
331         ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
332         switch (res) {
333             case NO_INIT:
334                 jniThrowException(env, "java/lang/IllegalStateException",
335                     "Surface has been abandoned");
336                 break;
337             default:
338                 // TODO: handle other error cases here.
339                 jniThrowRuntimeException(env, "dequeue buffer failed");
340         }
341         return;
342     }
343     // New GraphicBuffer object doesn't own the handle, thus the native buffer
344     // won't be freed when this object is destroyed.
345     sp<GraphicBuffer> buffer(new GraphicBuffer(anb, /*keepOwnership*/false));
346 
347     // Note that:
348     // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
349     // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
350     //    later.
351     // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
352 
353     // Finally, set the native info into image object.
354     Image_setNativeContext(env, image, buffer, fenceFd);
355 }
356 
ImageWriter_close(JNIEnv * env,jobject thiz,jlong nativeCtx)357 static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
358     ALOGV("%s:", __FUNCTION__);
359     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
360     if (ctx == NULL || thiz == NULL) {
361         // ImageWriter is already closed.
362         return;
363     }
364 
365     ANativeWindow* producer = ctx->getProducer();
366     if (producer != NULL) {
367         /**
368          * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
369          * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
370          * The producer listener will be cleared after disconnect call.
371          */
372         status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
373         /**
374          * This is not an error. if client calling process dies, the window will
375          * also die and all calls to it will return DEAD_OBJECT, thus it's already
376          * "disconnected"
377          */
378         if (res == DEAD_OBJECT) {
379             ALOGW("%s: While disconnecting ImageWriter from native window, the"
380                     " native window died already", __FUNCTION__);
381         } else if (res != OK) {
382             ALOGE("%s: native window disconnect failed: %s (%d)",
383                     __FUNCTION__, strerror(-res), res);
384             jniThrowRuntimeException(env, "Native window disconnect failed");
385             return;
386         }
387     }
388 
389     ctx->decStrong((void*)ImageWriter_init);
390 }
391 
ImageWriter_cancelImage(JNIEnv * env,jobject thiz,jlong nativeCtx,jobject image)392 static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
393     ALOGV("%s", __FUNCTION__);
394     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
395     if (ctx == NULL || thiz == NULL) {
396         ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
397         return;
398     }
399 
400     sp<ANativeWindow> anw = ctx->getProducer();
401 
402     GraphicBuffer *buffer = NULL;
403     int fenceFd = -1;
404     Image_getNativeContext(env, image, &buffer, &fenceFd);
405     if (buffer == NULL) {
406         // Cancel an already cancelled image is harmless.
407         return;
408     }
409 
410     // Unlock the image if it was locked
411     Image_unlockIfLocked(env, image);
412 
413     anw->cancelBuffer(anw.get(), buffer, fenceFd);
414 
415     Image_setNativeContext(env, image, NULL, -1);
416 }
417 
ImageWriter_queueImage(JNIEnv * env,jobject thiz,jlong nativeCtx,jobject image,jlong timestampNs,jint left,jint top,jint right,jint bottom)418 static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
419         jlong timestampNs, jint left, jint top, jint right, jint bottom) {
420     ALOGV("%s", __FUNCTION__);
421     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
422     if (ctx == NULL || thiz == NULL) {
423         jniThrowException(env, "java/lang/IllegalStateException",
424                 "ImageWriterContext is not initialized");
425         return;
426     }
427 
428     status_t res = OK;
429     sp<ANativeWindow> anw = ctx->getProducer();
430 
431     GraphicBuffer *buffer = NULL;
432     int fenceFd = -1;
433     Image_getNativeContext(env, image, &buffer, &fenceFd);
434     if (buffer == NULL) {
435         jniThrowException(env, "java/lang/IllegalStateException",
436                 "Image is not initialized");
437         return;
438     }
439 
440     // Unlock image if it was locked.
441     Image_unlockIfLocked(env, image);
442 
443     // Set timestamp
444     ALOGV("timestamp to be queued: %" PRId64, timestampNs);
445     res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
446     if (res != OK) {
447         jniThrowRuntimeException(env, "Set timestamp failed");
448         return;
449     }
450 
451     // Set crop
452     android_native_rect_t cropRect;
453     cropRect.left = left;
454     cropRect.top = top;
455     cropRect.right = right;
456     cropRect.bottom = bottom;
457     res = native_window_set_crop(anw.get(), &cropRect);
458     if (res != OK) {
459         jniThrowRuntimeException(env, "Set crop rect failed");
460         return;
461     }
462 
463     // Finally, queue input buffer
464     res = anw->queueBuffer(anw.get(), buffer, fenceFd);
465     if (res != OK) {
466         ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
467         switch (res) {
468             case NO_INIT:
469                 jniThrowException(env, "java/lang/IllegalStateException",
470                     "Surface has been abandoned");
471                 break;
472             default:
473                 // TODO: handle other error cases here.
474                 jniThrowRuntimeException(env, "Queue input buffer failed");
475         }
476         return;
477     }
478 
479     // Clear the image native context: end of this image's lifecycle in public API.
480     Image_setNativeContext(env, image, NULL, -1);
481 }
482 
ImageWriter_attachAndQueueImage(JNIEnv * env,jobject thiz,jlong nativeCtx,jlong nativeBuffer,jint imageFormat,jlong timestampNs,jint left,jint top,jint right,jint bottom)483 static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
484         jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint left, jint top,
485         jint right, jint bottom) {
486     ALOGV("%s", __FUNCTION__);
487     JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
488     if (ctx == NULL || thiz == NULL) {
489         jniThrowException(env, "java/lang/IllegalStateException",
490                 "ImageWriterContext is not initialized");
491         return -1;
492     }
493 
494     sp<Surface> surface = ctx->getProducer();
495     status_t res = OK;
496     if (!isFormatOpaque(imageFormat)) {
497         // TODO: need implement, see b/19962027
498         jniThrowRuntimeException(env,
499                 "nativeAttachImage for non-opaque image is not implement yet!!!");
500         return -1;
501     }
502 
503     if (!isFormatOpaque(ctx->getBufferFormat())) {
504         jniThrowException(env, "java/lang/IllegalStateException",
505                 "Trying to attach an opaque image into a non-opaque ImageWriter");
506         return -1;
507     }
508 
509     // Image is guaranteed to be from ImageReader at this point, so it is safe to
510     // cast to BufferItem pointer.
511     BufferItem* opaqueBuffer = reinterpret_cast<BufferItem*>(nativeBuffer);
512     if (opaqueBuffer == NULL) {
513         jniThrowException(env, "java/lang/IllegalStateException",
514                 "Image is not initialized or already closed");
515         return -1;
516     }
517 
518     // Step 1. Attach Image
519     res = surface->attachBuffer(opaqueBuffer->mGraphicBuffer.get());
520     if (res != OK) {
521         ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
522         switch (res) {
523             case NO_INIT:
524                 jniThrowException(env, "java/lang/IllegalStateException",
525                     "Surface has been abandoned");
526                 break;
527             default:
528                 // TODO: handle other error cases here.
529                 jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
530         }
531         return res;
532     }
533     sp < ANativeWindow > anw = surface;
534 
535     // Step 2. Set timestamp and crop. Note that we do not need unlock the image because
536     // it was not locked.
537     ALOGV("timestamp to be queued: %" PRId64, timestampNs);
538     res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
539     if (res != OK) {
540         jniThrowRuntimeException(env, "Set timestamp failed");
541         return res;
542     }
543 
544     android_native_rect_t cropRect;
545     cropRect.left = left;
546     cropRect.top = top;
547     cropRect.right = right;
548     cropRect.bottom = bottom;
549     res = native_window_set_crop(anw.get(), &cropRect);
550     if (res != OK) {
551         jniThrowRuntimeException(env, "Set crop rect failed");
552         return res;
553     }
554 
555     // Step 3. Queue Image.
556     res = anw->queueBuffer(anw.get(), opaqueBuffer->mGraphicBuffer.get(), /*fenceFd*/
557             -1);
558     if (res != OK) {
559         ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
560         switch (res) {
561             case NO_INIT:
562                 jniThrowException(env, "java/lang/IllegalStateException",
563                     "Surface has been abandoned");
564                 break;
565             default:
566                 // TODO: handle other error cases here.
567                 jniThrowRuntimeException(env, "Queue input buffer failed");
568         }
569         return res;
570     }
571 
572     // Do not set the image native context. Since it would overwrite the existing native context
573     // of the image that is from ImageReader, the subsequent image close will run into issues.
574 
575     return res;
576 }
577 
578 // --------------------------Image methods---------------------------------------
579 
Image_getNativeContext(JNIEnv * env,jobject thiz,GraphicBuffer ** buffer,int * fenceFd)580 static void Image_getNativeContext(JNIEnv* env, jobject thiz,
581         GraphicBuffer** buffer, int* fenceFd) {
582     ALOGV("%s", __FUNCTION__);
583     if (buffer != NULL) {
584         GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
585                   (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
586         *buffer = gb;
587     }
588 
589     if (fenceFd != NULL) {
590         *fenceFd = reinterpret_cast<jint>(env->GetIntField(
591                 thiz, gSurfaceImageClassInfo.mNativeFenceFd));
592     }
593 }
594 
Image_setNativeContext(JNIEnv * env,jobject thiz,sp<GraphicBuffer> buffer,int fenceFd)595 static void Image_setNativeContext(JNIEnv* env, jobject thiz,
596         sp<GraphicBuffer> buffer, int fenceFd) {
597     ALOGV("%s:", __FUNCTION__);
598     GraphicBuffer* p = NULL;
599     Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
600     if (buffer != 0) {
601         buffer->incStrong((void*)Image_setNativeContext);
602     }
603     if (p) {
604         p->decStrong((void*)Image_setNativeContext);
605     }
606     env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
607             reinterpret_cast<jlong>(buffer.get()));
608 
609     env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
610 }
611 
Image_unlockIfLocked(JNIEnv * env,jobject thiz)612 static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
613     ALOGV("%s", __FUNCTION__);
614     GraphicBuffer* buffer;
615     Image_getNativeContext(env, thiz, &buffer, NULL);
616     if (buffer == NULL) {
617         jniThrowException(env, "java/lang/IllegalStateException",
618                 "Image is not initialized");
619         return;
620     }
621 
622     // Is locked?
623     bool isLocked = false;
624     jobject planes = NULL;
625     if (!isFormatOpaque(buffer->getPixelFormat())) {
626         planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
627     }
628     isLocked = (planes != NULL);
629     if (isLocked) {
630         // no need to use fence here, as we it will be consumed by either cancel or queue buffer.
631         status_t res = buffer->unlock();
632         if (res != OK) {
633             jniThrowRuntimeException(env, "unlock buffer failed");
634         }
635         ALOGV("Successfully unlocked the image");
636     }
637 }
638 
Image_getWidth(JNIEnv * env,jobject thiz)639 static jint Image_getWidth(JNIEnv* env, jobject thiz) {
640     ALOGV("%s", __FUNCTION__);
641     GraphicBuffer* buffer;
642     Image_getNativeContext(env, thiz, &buffer, NULL);
643     if (buffer == NULL) {
644         jniThrowException(env, "java/lang/IllegalStateException",
645                 "Image is not initialized");
646         return -1;
647     }
648 
649     return buffer->getWidth();
650 }
651 
Image_getHeight(JNIEnv * env,jobject thiz)652 static jint Image_getHeight(JNIEnv* env, jobject thiz) {
653     ALOGV("%s", __FUNCTION__);
654     GraphicBuffer* buffer;
655     Image_getNativeContext(env, thiz, &buffer, NULL);
656     if (buffer == NULL) {
657         jniThrowException(env, "java/lang/IllegalStateException",
658                 "Image is not initialized");
659         return -1;
660     }
661 
662     return buffer->getHeight();
663 }
664 
Image_getFormat(JNIEnv * env,jobject thiz)665 static jint Image_getFormat(JNIEnv* env, jobject thiz) {
666     ALOGV("%s", __FUNCTION__);
667     GraphicBuffer* buffer;
668     Image_getNativeContext(env, thiz, &buffer, NULL);
669     if (buffer == NULL) {
670         jniThrowException(env, "java/lang/IllegalStateException",
671                 "Image is not initialized");
672         return 0;
673     }
674 
675     // ImageWriter doesn't support data space yet, assuming it is unknown.
676     PublicFormat publicFmt = android_view_Surface_mapHalFormatDataspaceToPublicFormat(
677             buffer->getPixelFormat(), HAL_DATASPACE_UNKNOWN);
678     return static_cast<jint>(publicFmt);
679 }
680 
Image_setFenceFd(JNIEnv * env,jobject thiz,int fenceFd)681 static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
682     ALOGV("%s:", __FUNCTION__);
683     env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
684 }
685 
Image_getLockedImage(JNIEnv * env,jobject thiz,LockedImage * image)686 static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
687     ALOGV("%s", __FUNCTION__);
688     GraphicBuffer* buffer;
689     int fenceFd = -1;
690     Image_getNativeContext(env, thiz, &buffer, &fenceFd);
691     if (buffer == NULL) {
692         jniThrowException(env, "java/lang/IllegalStateException",
693                 "Image is not initialized");
694         return;
695     }
696 
697     // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
698     const Rect noCrop(buffer->width, buffer->height);
699     status_t res = lockImageFromBuffer(
700             buffer, GRALLOC_USAGE_SW_WRITE_OFTEN, noCrop, fenceFd, image);
701     // Clear the fenceFd as it is already consumed by lock call.
702     Image_setFenceFd(env, thiz, /*fenceFd*/-1);
703     if (res != OK) {
704         jniThrowExceptionFmt(env, "java/lang/RuntimeException",
705                 "lock buffer failed for format 0x%x",
706                 buffer->getPixelFormat());
707         return;
708     }
709 
710     ALOGV("%s: Successfully locked the image", __FUNCTION__);
711     // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
712     // and we don't set them here.
713 }
714 
Image_getLockedImageInfo(JNIEnv * env,LockedImage * buffer,int idx,int32_t writerFormat,uint8_t ** base,uint32_t * size,int * pixelStride,int * rowStride)715 static void Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
716         int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
717     ALOGV("%s", __FUNCTION__);
718 
719     status_t res = getLockedImageInfo(buffer, idx, writerFormat, base, size,
720             pixelStride, rowStride);
721     if (res != OK) {
722         jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
723                              "Pixel format: 0x%x is unsupported", buffer->flexFormat);
724     }
725 }
726 
Image_createSurfacePlanes(JNIEnv * env,jobject thiz,int numPlanes,int writerFormat)727 static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
728         int numPlanes, int writerFormat) {
729     ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
730     int rowStride, pixelStride;
731     uint8_t *pData;
732     uint32_t dataSize;
733     jobject byteBuffer;
734 
735     int format = Image_getFormat(env, thiz);
736     if (isFormatOpaque(format) && numPlanes > 0) {
737         String8 msg;
738         msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
739                 " must be 0", format, numPlanes);
740         jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
741         return NULL;
742     }
743 
744     jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
745             /*initial_element*/NULL);
746     if (surfacePlanes == NULL) {
747         jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
748                 " probably out of memory");
749         return NULL;
750     }
751     if (isFormatOpaque(format)) {
752         return surfacePlanes;
753     }
754 
755     // Buildup buffer info: rowStride, pixelStride and byteBuffers.
756     LockedImage lockedImg = LockedImage();
757     Image_getLockedImage(env, thiz, &lockedImg);
758 
759     // Create all SurfacePlanes
760     PublicFormat publicWriterFormat = static_cast<PublicFormat>(writerFormat);
761     writerFormat = android_view_Surface_mapPublicFormatToHalFormat(publicWriterFormat);
762     for (int i = 0; i < numPlanes; i++) {
763         Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
764                 &pData, &dataSize, &pixelStride, &rowStride);
765         byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
766         if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
767             jniThrowException(env, "java/lang/IllegalStateException",
768                     "Failed to allocate ByteBuffer");
769             return NULL;
770         }
771 
772         // Finally, create this SurfacePlane.
773         jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
774                     gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
775         env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
776     }
777 
778     return surfacePlanes;
779 }
780 
781 } // extern "C"
782 
783 // ----------------------------------------------------------------------------
784 
785 static JNINativeMethod gImageWriterMethods[] = {
786     {"nativeClassInit",         "()V",                        (void*)ImageWriter_classInit },
787     {"nativeInit",              "(Ljava/lang/Object;Landroid/view/Surface;I)J",
788                                                               (void*)ImageWriter_init },
789     {"nativeClose",              "(J)V",                      (void*)ImageWriter_close },
790     {"nativeAttachAndQueueImage", "(JJIJIIII)I",          (void*)ImageWriter_attachAndQueueImage },
791     {"nativeDequeueInputImage", "(JLandroid/media/Image;)V",  (void*)ImageWriter_dequeueImage },
792     {"nativeQueueInputImage",   "(JLandroid/media/Image;JIIII)V",  (void*)ImageWriter_queueImage },
793     {"cancelImage",             "(JLandroid/media/Image;)V",   (void*)ImageWriter_cancelImage },
794 };
795 
796 static JNINativeMethod gImageMethods[] = {
797     {"nativeCreatePlanes",      "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
798                                                               (void*)Image_createSurfacePlanes },
799     {"nativeGetWidth",         "()I",                         (void*)Image_getWidth },
800     {"nativeGetHeight",        "()I",                         (void*)Image_getHeight },
801     {"nativeGetFormat",        "()I",                         (void*)Image_getFormat },
802 };
803 
register_android_media_ImageWriter(JNIEnv * env)804 int register_android_media_ImageWriter(JNIEnv *env) {
805 
806     int ret1 = AndroidRuntime::registerNativeMethods(env,
807                    "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
808 
809     int ret2 = AndroidRuntime::registerNativeMethods(env,
810                    "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
811 
812     return (ret1 || ret2);
813 }
814 
815