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