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