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