android_media_ImageWriter.cpp revision 1102e21b5dd0f79072e826932d0a3e3cb2f8c285
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 <utils/Log.h>
20#include <utils/String8.h>
21
22#include <gui/IProducerListener.h>
23#include <gui/Surface.h>
24#include <gui/CpuConsumer.h>
25#include <android_runtime/AndroidRuntime.h>
26#include <android_runtime/android_view_Surface.h>
27#include <camera3.h>
28
29#include <jni.h>
30#include <JNIHelp.h>
31
32#include <stdint.h>
33#include <inttypes.h>
34
35#define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
36
37#define IMAGE_BUFFER_JNI_ID           "mNativeBuffer"
38
39// ----------------------------------------------------------------------------
40
41using namespace android;
42
43enum {
44    IMAGE_WRITER_MAX_NUM_PLANES = 3,
45};
46
47static struct {
48    jmethodID postEventFromNative;
49    jfieldID mWriterFormat;
50} gImageWriterClassInfo;
51
52static struct {
53    jfieldID mNativeBuffer;
54    jfieldID mNativeFenceFd;
55    jfieldID mPlanes;
56} gSurfaceImageClassInfo;
57
58static struct {
59    jclass clazz;
60    jmethodID ctor;
61} gSurfacePlaneClassInfo;
62
63typedef CpuConsumer::LockedBuffer LockedImage;
64
65// ----------------------------------------------------------------------------
66
67class JNIImageWriterContext : public BnProducerListener {
68public:
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
77    void setProducer(const sp<Surface>& producer) { mProducer = producer; }
78    Surface* getProducer() { return mProducer.get(); }
79
80    void setBufferFormat(int format) { mFormat = format; }
81    int getBufferFormat() { return mFormat; }
82
83    void setBufferWidth(int width) { mWidth = width; }
84    int getBufferWidth() { return mWidth; }
85
86    void setBufferHeight(int height) { mHeight = height; }
87    int getBufferHeight() { return mHeight; }
88
89private:
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
101JNIImageWriterContext::JNIImageWriterContext(JNIEnv* env, jobject weakThiz, jclass clazz) :
102    mWeakThiz(env->NewGlobalRef(weakThiz)),
103    mClazz((jclass)env->NewGlobalRef(clazz)),
104    mFormat(0),
105    mWidth(-1),
106    mHeight(-1) {
107}
108
109JNIImageWriterContext::~JNIImageWriterContext() {
110    ALOGV("%s", __FUNCTION__);
111    bool needsDetach = false;
112    JNIEnv* env = getJNIEnv(&needsDetach);
113    if (env != NULL) {
114        env->DeleteGlobalRef(mWeakThiz);
115        env->DeleteGlobalRef(mClazz);
116    } else {
117        ALOGW("leaking JNI object references");
118    }
119    if (needsDetach) {
120        detachJNI();
121    }
122
123    mProducer.clear();
124}
125
126JNIEnv* JNIImageWriterContext::getJNIEnv(bool* needsDetach) {
127    ALOGV("%s", __FUNCTION__);
128    LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
129    *needsDetach = false;
130    JNIEnv* env = AndroidRuntime::getJNIEnv();
131    if (env == NULL) {
132        JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
133        JavaVM* vm = AndroidRuntime::getJavaVM();
134        int result = vm->AttachCurrentThread(&env, (void*) &args);
135        if (result != JNI_OK) {
136            ALOGE("thread attach failed: %#x", result);
137            return NULL;
138        }
139        *needsDetach = true;
140    }
141    return env;
142}
143
144void JNIImageWriterContext::detachJNI() {
145    ALOGV("%s", __FUNCTION__);
146    JavaVM* vm = AndroidRuntime::getJavaVM();
147    int result = vm->DetachCurrentThread();
148    if (result != JNI_OK) {
149        ALOGE("thread detach failed: %#x", result);
150    }
151}
152
153void JNIImageWriterContext::onBufferReleased() {
154    ALOGV("%s: buffer released", __FUNCTION__);
155    bool needsDetach = false;
156    JNIEnv* env = getJNIEnv(&needsDetach);
157    if (env != NULL) {
158        // Detach the buffer every time when a buffer consumption is done,
159        // need let this callback give a BufferItem, then only detach if it was attached to this
160        // Writer. Do the detach unconditionally for opaque format now. see b/19977520
161        if (mFormat == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
162            sp<Fence> fence;
163            sp<GraphicBuffer> buffer;
164            ALOGV("%s: One buffer is detached", __FUNCTION__);
165            mProducer->detachNextBuffer(&buffer, &fence);
166        }
167
168        env->CallStaticVoidMethod(mClazz, gImageWriterClassInfo.postEventFromNative, mWeakThiz);
169    } else {
170        ALOGW("onBufferReleased event will not posted");
171    }
172
173    if (needsDetach) {
174        detachJNI();
175    }
176}
177
178// ----------------------------------------------------------------------------
179
180extern "C" {
181
182// -------------------------------Private method declarations--------------
183
184static bool isPossiblyYUV(PixelFormat format);
185static void Image_setNativeContext(JNIEnv* env, jobject thiz,
186        sp<GraphicBuffer> buffer, int fenceFd);
187static void Image_getNativeContext(JNIEnv* env, jobject thiz,
188        GraphicBuffer** buffer, int* fenceFd);
189static void Image_unlockIfLocked(JNIEnv* env, jobject thiz);
190static bool isFormatOpaque(int format);
191
192// --------------------------ImageWriter methods---------------------------------------
193
194static void ImageWriter_classInit(JNIEnv* env, jclass clazz) {
195    ALOGV("%s:", __FUNCTION__);
196    jclass imageClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage");
197    LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
198            "can't find android/media/ImageWriter$WriterSurfaceImage");
199    gSurfaceImageClassInfo.mNativeBuffer = env->GetFieldID(
200            imageClazz, IMAGE_BUFFER_JNI_ID, "J");
201    LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeBuffer == NULL,
202            "can't find android/media/ImageWriter$WriterSurfaceImage.%s", IMAGE_BUFFER_JNI_ID);
203
204    gSurfaceImageClassInfo.mNativeFenceFd = env->GetFieldID(
205            imageClazz, "mNativeFenceFd", "I");
206    LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mNativeFenceFd == NULL,
207            "can't find android/media/ImageWriter$WriterSurfaceImage.mNativeFenceFd");
208
209    gSurfaceImageClassInfo.mPlanes = env->GetFieldID(
210            imageClazz, "mPlanes", "[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;");
211    LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mPlanes == NULL,
212            "can't find android/media/ImageWriter$WriterSurfaceImage.mPlanes");
213
214    gImageWriterClassInfo.postEventFromNative = env->GetStaticMethodID(
215            clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
216    LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.postEventFromNative == NULL,
217                        "can't find android/media/ImageWriter.postEventFromNative");
218
219    gImageWriterClassInfo.mWriterFormat = env->GetFieldID(
220            clazz, "mWriterFormat", "I");
221    LOG_ALWAYS_FATAL_IF(gImageWriterClassInfo.mWriterFormat == NULL,
222                        "can't find android/media/ImageWriter.mWriterFormat");
223
224    jclass planeClazz = env->FindClass("android/media/ImageWriter$WriterSurfaceImage$SurfacePlane");
225    LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
226    // FindClass only gives a local reference of jclass object.
227    gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
228    gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
229            "(Landroid/media/ImageWriter$WriterSurfaceImage;IILjava/nio/ByteBuffer;)V");
230    LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
231            "Can not find SurfacePlane constructor");
232}
233
234static jlong ImageWriter_init(JNIEnv* env, jobject thiz, jobject weakThiz, jobject jsurface,
235        jint maxImages) {
236    status_t res;
237
238    ALOGV("%s: maxImages:%d", __FUNCTION__, maxImages);
239
240    sp<Surface> surface(android_view_Surface_getSurface(env, jsurface));
241    if (surface == NULL) {
242        jniThrowException(env,
243                "java/lang/IllegalArgumentException",
244                "The surface has been released");
245        return 0;
246     }
247    sp<IGraphicBufferProducer> bufferProducer = surface->getIGraphicBufferProducer();
248
249    jclass clazz = env->GetObjectClass(thiz);
250    if (clazz == NULL) {
251        jniThrowRuntimeException(env, "Can't find android/graphics/ImageWriter");
252        return 0;
253    }
254    sp<JNIImageWriterContext> ctx(new JNIImageWriterContext(env, weakThiz, clazz));
255
256    sp<Surface> producer = new Surface(bufferProducer, /*controlledByApp*/false);
257    ctx->setProducer(producer);
258    /**
259     * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not connectable
260     * after disconnect. MEDIA or CAMERA are treated the same internally. The producer listener
261     * will be cleared after disconnect call.
262     */
263    producer->connect(/*api*/NATIVE_WINDOW_API_CAMERA, /*listener*/ctx);
264    jlong nativeCtx = reinterpret_cast<jlong>(ctx.get());
265
266    // Get the dimension and format of the producer.
267    sp<ANativeWindow> anw = producer;
268    int32_t width, height, format;
269    if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
270        ALOGE("%s: Query Surface width failed: %s (%d)", __FUNCTION__, strerror(-res), res);
271        jniThrowRuntimeException(env, "Failed to query Surface width");
272        return 0;
273    }
274    ctx->setBufferWidth(width);
275
276    if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
277        ALOGE("%s: Query Surface height failed: %s (%d)", __FUNCTION__, strerror(-res), res);
278        jniThrowRuntimeException(env, "Failed to query Surface height");
279        return 0;
280    }
281    ctx->setBufferHeight(height);
282
283    if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &format)) != OK) {
284        ALOGE("%s: Query Surface format failed: %s (%d)", __FUNCTION__, strerror(-res), res);
285        jniThrowRuntimeException(env, "Failed to query Surface format");
286        return 0;
287    }
288    ctx->setBufferFormat(format);
289    env->SetIntField(thiz, gImageWriterClassInfo.mWriterFormat, reinterpret_cast<jint>(format));
290
291
292    if (!isFormatOpaque(format)) {
293        res = native_window_set_usage(anw.get(), GRALLOC_USAGE_SW_WRITE_OFTEN);
294        if (res != OK) {
295            ALOGE("%s: Configure usage %08x for format %08x failed: %s (%d)",
296                  __FUNCTION__, static_cast<unsigned int>(GRALLOC_USAGE_SW_WRITE_OFTEN),
297                  format, strerror(-res), res);
298            jniThrowRuntimeException(env, "Failed to SW_WRITE_OFTEN configure usage");
299            return 0;
300        }
301    }
302
303    int minUndequeuedBufferCount = 0;
304    res = anw->query(anw.get(),
305                NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufferCount);
306    if (res != OK) {
307        ALOGE("%s: Query producer undequeued buffer count failed: %s (%d)",
308                __FUNCTION__, strerror(-res), res);
309        jniThrowRuntimeException(env, "Query producer undequeued buffer count failed");
310        return 0;
311     }
312
313    size_t totalBufferCount = maxImages + minUndequeuedBufferCount;
314    res = native_window_set_buffer_count(anw.get(), totalBufferCount);
315    if (res != OK) {
316        ALOGE("%s: Set buffer count failed: %s (%d)", __FUNCTION__, strerror(-res), res);
317        jniThrowRuntimeException(env, "Set buffer count failed");
318        return 0;
319    }
320
321    if (ctx != 0) {
322        ctx->incStrong((void*)ImageWriter_init);
323    }
324    return nativeCtx;
325}
326
327static void ImageWriter_dequeueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
328    ALOGV("%s", __FUNCTION__);
329    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
330    if (ctx == NULL || thiz == NULL) {
331        jniThrowException(env, "java/lang/IllegalStateException",
332                "ImageWriterContext is not initialized");
333        return;
334    }
335
336    sp<ANativeWindow> anw = ctx->getProducer();
337    android_native_buffer_t *anb = NULL;
338    int fenceFd = -1;
339    status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
340    if (res != OK) {
341        // TODO: handle different error cases here.
342        ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
343        jniThrowRuntimeException(env, "dequeue buffer failed");
344        return;
345    }
346    // New GraphicBuffer object doesn't own the handle, thus the native buffer
347    // won't be freed when this object is destroyed.
348    sp<GraphicBuffer> buffer(new GraphicBuffer(anb, /*keepOwnership*/false));
349
350    // Note that:
351    // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
352    // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
353    //    later.
354    // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
355
356    // Finally, set the native info into image object.
357    Image_setNativeContext(env, image, buffer, fenceFd);
358}
359
360static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
361    ALOGV("%s:", __FUNCTION__);
362    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
363    if (ctx == NULL || thiz == NULL) {
364        jniThrowException(env, "java/lang/IllegalStateException",
365                "ImageWriterContext is not initialized");
366        return;
367    }
368
369    ANativeWindow* producer = ctx->getProducer();
370    if (producer != NULL) {
371        /**
372         * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
373         * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
374         * The producer listener will be cleared after disconnect call.
375         */
376        status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
377        /**
378         * This is not an error. if client calling process dies, the window will
379         * also die and all calls to it will return DEAD_OBJECT, thus it's already
380         * "disconnected"
381         */
382        if (res == DEAD_OBJECT) {
383            ALOGW("%s: While disconnecting ImageWriter from native window, the"
384                    " native window died already", __FUNCTION__);
385        } else if (res != OK) {
386            ALOGE("%s: native window disconnect failed: %s (%d)",
387                    __FUNCTION__, strerror(-res), res);
388            jniThrowRuntimeException(env, "Native window disconnect failed");
389            return;
390        }
391    }
392
393    ctx->decStrong((void*)ImageWriter_init);
394}
395
396static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
397    ALOGV("%s", __FUNCTION__);
398    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
399    if (ctx == NULL || thiz == NULL) {
400        jniThrowException(env, "java/lang/IllegalStateException",
401                "ImageWriterContext is not initialized");
402        return;
403    }
404
405    sp<ANativeWindow> anw = ctx->getProducer();
406
407    GraphicBuffer *buffer = NULL;
408    int fenceFd = -1;
409    Image_getNativeContext(env, image, &buffer, &fenceFd);
410    if (buffer == NULL) {
411        jniThrowException(env, "java/lang/IllegalStateException",
412                "Image is not initialized");
413        return;
414    }
415
416    // Unlock the image if it was locked
417    Image_unlockIfLocked(env, image);
418
419    anw->cancelBuffer(anw.get(), buffer, fenceFd);
420
421    Image_setNativeContext(env, image, NULL, -1);
422}
423
424static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
425        jlong timestampNs, jint left, jint top, jint right, jint bottom) {
426    ALOGV("%s", __FUNCTION__);
427    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
428    if (ctx == NULL || thiz == NULL) {
429        jniThrowException(env, "java/lang/IllegalStateException",
430                "ImageWriterContext is not initialized");
431        return;
432    }
433
434    status_t res = OK;
435    sp<ANativeWindow> anw = ctx->getProducer();
436
437    GraphicBuffer *buffer = NULL;
438    int fenceFd = -1;
439    Image_getNativeContext(env, image, &buffer, &fenceFd);
440    if (buffer == NULL) {
441        jniThrowException(env, "java/lang/IllegalStateException",
442                "Image is not initialized");
443        return;
444    }
445
446    // Unlock image if it was locked.
447    Image_unlockIfLocked(env, image);
448
449    // Set timestamp
450    ALOGV("timestamp to be queued: %" PRId64, timestampNs);
451    res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
452    if (res != OK) {
453        jniThrowRuntimeException(env, "Set timestamp failed");
454        return;
455    }
456
457    // Set crop
458    android_native_rect_t cropRect;
459    cropRect.left = left;
460    cropRect.top = top;
461    cropRect.right = right;
462    cropRect.bottom = bottom;
463    res = native_window_set_crop(anw.get(), &cropRect);
464    if (res != OK) {
465        jniThrowRuntimeException(env, "Set crop rect failed");
466        return;
467    }
468
469    // Finally, queue input buffer
470    res = anw->queueBuffer(anw.get(), buffer, fenceFd);
471    if (res != OK) {
472        jniThrowRuntimeException(env, "Queue input buffer failed");
473        return;
474    }
475
476    // Clear the image native context: end of this image's lifecycle in public API.
477    Image_setNativeContext(env, image, NULL, -1);
478}
479
480static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
481        jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint left, jint top,
482        jint right, jint bottom) {
483    ALOGV("%s", __FUNCTION__);
484    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
485    if (ctx == NULL || thiz == NULL) {
486        jniThrowException(env, "java/lang/IllegalStateException",
487                "ImageWriterContext is not initialized");
488        return -1;
489    }
490
491    sp<Surface> surface = ctx->getProducer();
492    status_t res = OK;
493    if (!isFormatOpaque(imageFormat)) {
494        // TODO: need implement, see b/19962027
495        jniThrowRuntimeException(env,
496                "nativeAttachImage for non-opaque image is not implement yet!!!");
497        return -1;
498    }
499
500    if (!isFormatOpaque(ctx->getBufferFormat())) {
501        jniThrowException(env, "java/lang/IllegalStateException",
502                "Trying to attach an opaque image into a non-opaque ImageWriter");
503        return -1;
504    }
505
506    // Image is guaranteed to be from ImageReader at this point, so it is safe to
507    // cast to BufferItem pointer.
508    BufferItem* opaqueBuffer = reinterpret_cast<BufferItem*>(nativeBuffer);
509    if (opaqueBuffer == NULL) {
510        jniThrowException(env, "java/lang/IllegalStateException",
511                "Image is not initialized or already closed");
512        return -1;
513    }
514
515    // Step 1. Attach Image
516    res = surface->attachBuffer(opaqueBuffer->mGraphicBuffer.get());
517    if (res != OK) {
518        // TODO: handle different error case separately.
519        ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
520        jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
521        return res;
522    }
523    sp < ANativeWindow > anw = surface;
524
525    // Step 2. Set timestamp and crop. Note that we do not need unlock the image because
526    // it was not locked.
527    ALOGV("timestamp to be queued: %" PRId64, timestampNs);
528    res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
529    if (res != OK) {
530        jniThrowRuntimeException(env, "Set timestamp failed");
531        return res;
532    }
533
534    android_native_rect_t cropRect;
535    cropRect.left = left;
536    cropRect.top = top;
537    cropRect.right = right;
538    cropRect.bottom = bottom;
539    res = native_window_set_crop(anw.get(), &cropRect);
540    if (res != OK) {
541        jniThrowRuntimeException(env, "Set crop rect failed");
542        return res;
543    }
544
545    // Step 3. Queue Image.
546    res = anw->queueBuffer(anw.get(), opaqueBuffer->mGraphicBuffer.get(), /*fenceFd*/
547            -1);
548    if (res != OK) {
549        jniThrowRuntimeException(env, "Queue input buffer failed");
550        return res;
551    }
552
553    // Do not set the image native context. Since it would overwrite the existing native context
554    // of the image that is from ImageReader, the subsequent image close will run into issues.
555
556    return res;
557}
558
559// --------------------------Image methods---------------------------------------
560
561static void Image_getNativeContext(JNIEnv* env, jobject thiz,
562        GraphicBuffer** buffer, int* fenceFd) {
563    ALOGV("%s", __FUNCTION__);
564    if (buffer != NULL) {
565        GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
566                  (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
567        *buffer = gb;
568    }
569
570    if (fenceFd != NULL) {
571        *fenceFd = reinterpret_cast<jint>(env->GetIntField(
572                thiz, gSurfaceImageClassInfo.mNativeFenceFd));
573    }
574}
575
576static void Image_setNativeContext(JNIEnv* env, jobject thiz,
577        sp<GraphicBuffer> buffer, int fenceFd) {
578    ALOGV("%s:", __FUNCTION__);
579    GraphicBuffer* p = NULL;
580    Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
581    if (buffer != 0) {
582        buffer->incStrong((void*)Image_setNativeContext);
583    }
584    if (p) {
585        p->decStrong((void*)Image_setNativeContext);
586    }
587    env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
588            reinterpret_cast<jlong>(buffer.get()));
589
590    env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
591}
592
593static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
594    ALOGV("%s", __FUNCTION__);
595    GraphicBuffer* buffer;
596    Image_getNativeContext(env, thiz, &buffer, NULL);
597    if (buffer == NULL) {
598        jniThrowException(env, "java/lang/IllegalStateException",
599                "Image is not initialized");
600        return;
601    }
602
603    // Is locked?
604    bool isLocked = false;
605    jobject planes = NULL;
606    if (!isFormatOpaque(buffer->getPixelFormat())) {
607        planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
608    }
609    isLocked = (planes != NULL);
610    if (isLocked) {
611        // no need to use fence here, as we it will be consumed by either cancel or queue buffer.
612        status_t res = buffer->unlock();
613        if (res != OK) {
614            jniThrowRuntimeException(env, "unlock buffer failed");
615        }
616        ALOGV("Successfully unlocked the image");
617    }
618}
619
620static jint Image_getWidth(JNIEnv* env, jobject thiz) {
621    ALOGV("%s", __FUNCTION__);
622    GraphicBuffer* buffer;
623    Image_getNativeContext(env, thiz, &buffer, NULL);
624    if (buffer == NULL) {
625        jniThrowException(env, "java/lang/IllegalStateException",
626                "Image is not initialized");
627        return -1;
628    }
629
630    return buffer->getWidth();
631}
632
633static jint Image_getHeight(JNIEnv* env, jobject thiz) {
634    ALOGV("%s", __FUNCTION__);
635    GraphicBuffer* buffer;
636    Image_getNativeContext(env, thiz, &buffer, NULL);
637    if (buffer == NULL) {
638        jniThrowException(env, "java/lang/IllegalStateException",
639                "Image is not initialized");
640        return -1;
641    }
642
643    return buffer->getHeight();
644}
645
646// Some formats like JPEG defined with different values between android.graphics.ImageFormat and
647// graphics.h, need convert to the one defined in graphics.h here.
648static int Image_getPixelFormat(JNIEnv* env, int format) {
649    int jpegFormat;
650    jfieldID fid;
651
652    ALOGV("%s: format = 0x%x", __FUNCTION__, format);
653
654    jclass imageFormatClazz = env->FindClass("android/graphics/ImageFormat");
655    ALOG_ASSERT(imageFormatClazz != NULL);
656
657    fid = env->GetStaticFieldID(imageFormatClazz, "JPEG", "I");
658    jpegFormat = env->GetStaticIntField(imageFormatClazz, fid);
659
660    // Translate the JPEG to BLOB for camera purpose.
661    if (format == jpegFormat) {
662        format = HAL_PIXEL_FORMAT_BLOB;
663    }
664
665    return format;
666}
667
668static jint Image_getFormat(JNIEnv* env, jobject thiz) {
669    ALOGV("%s", __FUNCTION__);
670    GraphicBuffer* buffer;
671    Image_getNativeContext(env, thiz, &buffer, NULL);
672    if (buffer == NULL) {
673        jniThrowException(env, "java/lang/IllegalStateException",
674                "Image is not initialized");
675        return 0;
676    }
677
678    return Image_getPixelFormat(env, buffer->getPixelFormat());
679}
680
681static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
682    ALOGV("%s:", __FUNCTION__);
683    env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
684}
685
686static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
687    ALOGV("%s", __FUNCTION__);
688    GraphicBuffer* buffer;
689    int fenceFd = -1;
690    Image_getNativeContext(env, thiz, &buffer, &fenceFd);
691    if (buffer == NULL) {
692        jniThrowException(env, "java/lang/IllegalStateException",
693                "Image is not initialized");
694        return;
695    }
696
697    void* pData = NULL;
698    android_ycbcr ycbcr = android_ycbcr();
699    status_t res;
700    int format = Image_getFormat(env, thiz);
701    int flexFormat = format;
702    if (isPossiblyYUV(format)) {
703        // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
704        res = buffer->lockAsyncYCbCr(GRALLOC_USAGE_SW_WRITE_OFTEN, &ycbcr, fenceFd);
705        // Clear the fenceFd as it is already consumed by lock call.
706        Image_setFenceFd(env, thiz, /*fenceFd*/-1);
707        if (res != OK) {
708            jniThrowRuntimeException(env, "lockAsyncYCbCr failed for YUV buffer");
709            return;
710        }
711        pData = ycbcr.y;
712        flexFormat = HAL_PIXEL_FORMAT_YCbCr_420_888;
713    }
714
715    // lockAsyncYCbCr for YUV is unsuccessful.
716    if (pData == NULL) {
717        res = buffer->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &pData, fenceFd);
718        if (res != OK) {
719            jniThrowRuntimeException(env, "lockAsync failed");
720            return;
721        }
722    }
723
724    image->data = reinterpret_cast<uint8_t*>(pData);
725    image->width = buffer->getWidth();
726    image->height = buffer->getHeight();
727    image->format = format;
728    image->flexFormat = flexFormat;
729    image->stride = (ycbcr.y != NULL) ? static_cast<uint32_t>(ycbcr.ystride) : buffer->getStride();
730
731    image->dataCb = reinterpret_cast<uint8_t*>(ycbcr.cb);
732    image->dataCr = reinterpret_cast<uint8_t*>(ycbcr.cr);
733    image->chromaStride = static_cast<uint32_t>(ycbcr.cstride);
734    image->chromaStep = static_cast<uint32_t>(ycbcr.chroma_step);
735    ALOGV("Successfully locked the image");
736    // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
737    // and we don't set them here.
738}
739
740static bool usingRGBAToJpegOverride(int32_t bufferFormat, int32_t writerCtxFormat) {
741    return writerCtxFormat == HAL_PIXEL_FORMAT_BLOB && bufferFormat == HAL_PIXEL_FORMAT_RGBA_8888;
742}
743
744static int32_t applyFormatOverrides(int32_t bufferFormat, int32_t writerCtxFormat)
745{
746    // Using HAL_PIXEL_FORMAT_RGBA_8888 gralloc buffers containing JPEGs to get around SW
747    // write limitations for some platforms (b/17379185).
748    if (usingRGBAToJpegOverride(bufferFormat, writerCtxFormat)) {
749        return HAL_PIXEL_FORMAT_BLOB;
750    }
751    return bufferFormat;
752}
753
754static uint32_t Image_getJpegSize(LockedImage* buffer, bool usingRGBAOverride) {
755    ALOGV("%s", __FUNCTION__);
756    ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
757    uint32_t size = 0;
758    uint32_t width = buffer->width;
759    uint8_t* jpegBuffer = buffer->data;
760
761    if (usingRGBAOverride) {
762        width = (buffer->width + buffer->stride * (buffer->height - 1)) * 4;
763    }
764
765    // First check for JPEG transport header at the end of the buffer
766    uint8_t* header = jpegBuffer + (width - sizeof(struct camera3_jpeg_blob));
767    struct camera3_jpeg_blob *blob = (struct camera3_jpeg_blob*)(header);
768    if (blob->jpeg_blob_id == CAMERA3_JPEG_BLOB_ID) {
769        size = blob->jpeg_size;
770        ALOGV("%s: Jpeg size = %d", __FUNCTION__, size);
771    }
772
773    // failed to find size, default to whole buffer
774    if (size == 0) {
775        /*
776         * This is a problem because not including the JPEG header
777         * means that in certain rare situations a regular JPEG blob
778         * will be misidentified as having a header, in which case
779         * we will get a garbage size value.
780         */
781        ALOGW("%s: No JPEG header detected, defaulting to size=width=%d",
782                __FUNCTION__, width);
783        size = width;
784    }
785
786    return size;
787}
788
789static void Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
790        int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
791    ALOGV("%s", __FUNCTION__);
792    ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
793    ALOG_ASSERT(base != NULL, "base is NULL!!!");
794    ALOG_ASSERT(size != NULL, "size is NULL!!!");
795    ALOG_ASSERT(pixelStride != NULL, "pixelStride is NULL!!!");
796    ALOG_ASSERT(rowStride != NULL, "rowStride is NULL!!!");
797    ALOG_ASSERT((idx < IMAGE_WRITER_MAX_NUM_PLANES) && (idx >= 0));
798
799    ALOGV("%s: buffer: %p", __FUNCTION__, buffer);
800
801    uint32_t dataSize, ySize, cSize, cStride;
802    uint32_t pStride = 0, rStride = 0;
803    uint8_t *cb, *cr;
804    uint8_t *pData = NULL;
805    int bytesPerPixel = 0;
806
807    dataSize = ySize = cSize = cStride = 0;
808    int32_t fmt = buffer->flexFormat;
809
810    bool usingRGBAOverride = usingRGBAToJpegOverride(fmt, writerFormat);
811    fmt = applyFormatOverrides(fmt, writerFormat);
812    switch (fmt) {
813        case HAL_PIXEL_FORMAT_YCbCr_420_888:
814            pData =
815                (idx == 0) ?
816                    buffer->data :
817                (idx == 1) ?
818                    buffer->dataCb :
819                buffer->dataCr;
820            // only map until last pixel
821            if (idx == 0) {
822                pStride = 1;
823                rStride = buffer->stride;
824                dataSize = buffer->stride * (buffer->height - 1) + buffer->width;
825            } else {
826                pStride = buffer->chromaStep;
827                rStride = buffer->chromaStride;
828                dataSize = buffer->chromaStride * (buffer->height / 2 - 1) +
829                        buffer->chromaStep * (buffer->width / 2 - 1) + 1;
830            }
831            break;
832        // NV21
833        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
834            cr = buffer->data + (buffer->stride * buffer->height);
835            cb = cr + 1;
836            // only map until last pixel
837            ySize = buffer->width * (buffer->height - 1) + buffer->width;
838            cSize = buffer->width * (buffer->height / 2 - 1) + buffer->width - 1;
839
840            pData =
841                (idx == 0) ?
842                    buffer->data :
843                (idx == 1) ?
844                    cb:
845                cr;
846
847            dataSize = (idx == 0) ? ySize : cSize;
848            pStride = (idx == 0) ? 1 : 2;
849            rStride = buffer->width;
850            break;
851        case HAL_PIXEL_FORMAT_YV12:
852            // Y and C stride need to be 16 pixel aligned.
853            LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
854                                "Stride is not 16 pixel aligned %d", buffer->stride);
855
856            ySize = buffer->stride * buffer->height;
857            cStride = ALIGN(buffer->stride / 2, 16);
858            cr = buffer->data + ySize;
859            cSize = cStride * buffer->height / 2;
860            cb = cr + cSize;
861
862            pData =
863                (idx == 0) ?
864                    buffer->data :
865                (idx == 1) ?
866                    cb :
867                cr;
868            dataSize = (idx == 0) ? ySize : cSize;
869            pStride = 1;
870            rStride = (idx == 0) ? buffer->stride : ALIGN(buffer->stride / 2, 16);
871            break;
872        case HAL_PIXEL_FORMAT_Y8:
873            // Single plane, 8bpp.
874            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
875
876            pData = buffer->data;
877            dataSize = buffer->stride * buffer->height;
878            pStride = 1;
879            rStride = buffer->stride;
880            break;
881        case HAL_PIXEL_FORMAT_Y16:
882            bytesPerPixel = 2;
883            // Single plane, 16bpp, strides are specified in pixels, not in bytes
884            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
885
886            pData = buffer->data;
887            dataSize = buffer->stride * buffer->height * bytesPerPixel;
888            pStride = bytesPerPixel;
889            rStride = buffer->stride * 2;
890            break;
891        case HAL_PIXEL_FORMAT_BLOB:
892            // Used for JPEG data, height must be 1, width == size, single plane.
893            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
894            ALOG_ASSERT(buffer->height == 1, "JPEG should has height value %d", buffer->height);
895
896            pData = buffer->data;
897            dataSize = Image_getJpegSize(buffer, usingRGBAOverride);
898            pStride = bytesPerPixel;
899            rowStride = 0;
900            break;
901        case HAL_PIXEL_FORMAT_RAW16:
902            // Single plane 16bpp bayer data.
903            bytesPerPixel = 2;
904            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
905            pData = buffer->data;
906            dataSize = buffer->stride * buffer->height * bytesPerPixel;
907            pStride = bytesPerPixel;
908            rStride = buffer->stride * 2;
909            break;
910        case HAL_PIXEL_FORMAT_RAW10:
911            // Single plane 10bpp bayer data.
912            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
913            LOG_ALWAYS_FATAL_IF(buffer->width % 4,
914                                "Width is not multiple of 4 %d", buffer->width);
915            LOG_ALWAYS_FATAL_IF(buffer->height % 2,
916                                "Height is not even %d", buffer->height);
917            LOG_ALWAYS_FATAL_IF(buffer->stride < (buffer->width * 10 / 8),
918                                "stride (%d) should be at least %d",
919                                buffer->stride, buffer->width * 10 / 8);
920            pData = buffer->data;
921            dataSize = buffer->stride * buffer->height;
922            pStride = 0;
923            rStride = buffer->stride;
924            break;
925        case HAL_PIXEL_FORMAT_RGBA_8888:
926        case HAL_PIXEL_FORMAT_RGBX_8888:
927            // Single plane, 32bpp.
928            bytesPerPixel = 4;
929            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
930            pData = buffer->data;
931            dataSize = buffer->stride * buffer->height * bytesPerPixel;
932            pStride = bytesPerPixel;
933            rStride = buffer->stride * 4;
934            break;
935        case HAL_PIXEL_FORMAT_RGB_565:
936            // Single plane, 16bpp.
937            bytesPerPixel = 2;
938            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
939            pData = buffer->data;
940            dataSize = buffer->stride * buffer->height * bytesPerPixel;
941            pStride = bytesPerPixel;
942            rStride = buffer->stride * 2;
943            break;
944        case HAL_PIXEL_FORMAT_RGB_888:
945            // Single plane, 24bpp.
946            bytesPerPixel = 3;
947            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
948            pData = buffer->data;
949            dataSize = buffer->stride * buffer->height * bytesPerPixel;
950            pStride = bytesPerPixel;
951            rStride = buffer->stride * 3;
952            break;
953        default:
954            jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
955                                 "Pixel format: 0x%x is unsupported", fmt);
956            break;
957    }
958
959    *base = pData;
960    *size = dataSize;
961    *pixelStride = pStride;
962    *rowStride = rStride;
963}
964
965static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
966        int numPlanes, int writerFormat) {
967    ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
968    int rowStride, pixelStride;
969    uint8_t *pData;
970    uint32_t dataSize;
971    jobject byteBuffer;
972
973    int format = Image_getFormat(env, thiz);
974    if (isFormatOpaque(format) && numPlanes > 0) {
975        String8 msg;
976        msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
977                " must be 0", format, numPlanes);
978        jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
979        return NULL;
980    }
981
982    jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
983            /*initial_element*/NULL);
984    if (surfacePlanes == NULL) {
985        jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
986                " probably out of memory");
987        return NULL;
988    }
989    if (isFormatOpaque(format)) {
990        return surfacePlanes;
991    }
992
993    // Buildup buffer info: rowStride, pixelStride and byteBuffers.
994    LockedImage lockedImg = LockedImage();
995    Image_getLockedImage(env, thiz, &lockedImg);
996
997    // Create all SurfacePlanes
998    writerFormat = Image_getPixelFormat(env, writerFormat);
999    for (int i = 0; i < numPlanes; i++) {
1000        Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
1001                &pData, &dataSize, &pixelStride, &rowStride);
1002        byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1003        if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1004            jniThrowException(env, "java/lang/IllegalStateException",
1005                    "Failed to allocate ByteBuffer");
1006            return NULL;
1007        }
1008
1009        // Finally, create this SurfacePlane.
1010        jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1011                    gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1012        env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1013    }
1014
1015    return surfacePlanes;
1016}
1017
1018// -------------------------------Private convenience methods--------------------
1019
1020static bool isFormatOpaque(int format) {
1021    // Only treat IMPLEMENTATION_DEFINED as an opaque format for now.
1022    return format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
1023}
1024
1025static bool isPossiblyYUV(PixelFormat format) {
1026    switch (static_cast<int>(format)) {
1027        case HAL_PIXEL_FORMAT_RGBA_8888:
1028        case HAL_PIXEL_FORMAT_RGBX_8888:
1029        case HAL_PIXEL_FORMAT_RGB_888:
1030        case HAL_PIXEL_FORMAT_RGB_565:
1031        case HAL_PIXEL_FORMAT_BGRA_8888:
1032        case HAL_PIXEL_FORMAT_Y8:
1033        case HAL_PIXEL_FORMAT_Y16:
1034        case HAL_PIXEL_FORMAT_RAW16:
1035        case HAL_PIXEL_FORMAT_RAW10:
1036        case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1037        case HAL_PIXEL_FORMAT_BLOB:
1038        case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1039            return false;
1040
1041        case HAL_PIXEL_FORMAT_YV12:
1042        case HAL_PIXEL_FORMAT_YCbCr_420_888:
1043        case HAL_PIXEL_FORMAT_YCbCr_422_SP:
1044        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
1045        case HAL_PIXEL_FORMAT_YCbCr_422_I:
1046        default:
1047            return true;
1048    }
1049}
1050
1051} // extern "C"
1052
1053// ----------------------------------------------------------------------------
1054
1055static JNINativeMethod gImageWriterMethods[] = {
1056    {"nativeClassInit",         "()V",                        (void*)ImageWriter_classInit },
1057    {"nativeInit",              "(Ljava/lang/Object;Landroid/view/Surface;I)J",
1058                                                              (void*)ImageWriter_init },
1059    {"nativeClose",              "(J)V",                      (void*)ImageWriter_close },
1060    {"nativeAttachAndQueueImage", "(JJIJIIII)I",          (void*)ImageWriter_attachAndQueueImage },
1061    {"nativeDequeueInputImage", "(JLandroid/media/Image;)V",  (void*)ImageWriter_dequeueImage },
1062    {"nativeQueueInputImage",   "(JLandroid/media/Image;JIIII)V",  (void*)ImageWriter_queueImage },
1063    {"cancelImage",             "(JLandroid/media/Image;)V",   (void*)ImageWriter_cancelImage },
1064};
1065
1066static JNINativeMethod gImageMethods[] = {
1067    {"nativeCreatePlanes",      "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
1068                                                              (void*)Image_createSurfacePlanes },
1069    {"nativeGetWidth",         "()I",                         (void*)Image_getWidth },
1070    {"nativeGetHeight",        "()I",                         (void*)Image_getHeight },
1071    {"nativeGetFormat",        "()I",                         (void*)Image_getFormat },
1072};
1073
1074int register_android_media_ImageWriter(JNIEnv *env) {
1075
1076    int ret1 = AndroidRuntime::registerNativeMethods(env,
1077                   "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1078
1079    int ret2 = AndroidRuntime::registerNativeMethods(env,
1080                   "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1081
1082    return (ret1 || ret2);
1083}
1084
1085