android_media_ImageWriter.cpp revision dc6bb24a3c2c830c909523e8d7d999fb556fb77d
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        ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
342        switch (res) {
343            case NO_INIT:
344                jniThrowException(env, "java/lang/IllegalStateException",
345                    "Surface has been abandoned");
346                break;
347            default:
348                // TODO: handle other error cases here.
349                jniThrowRuntimeException(env, "dequeue buffer failed");
350        }
351        return;
352    }
353    // New GraphicBuffer object doesn't own the handle, thus the native buffer
354    // won't be freed when this object is destroyed.
355    sp<GraphicBuffer> buffer(new GraphicBuffer(anb, /*keepOwnership*/false));
356
357    // Note that:
358    // 1. No need to lock buffer now, will only lock it when the first getPlanes() is called.
359    // 2. Fence will be saved to mNativeFenceFd, and will consumed by lock/queue/cancel buffer
360    //    later.
361    // 3. need use lockAsync here, as it will handle the dequeued fence for us automatically.
362
363    // Finally, set the native info into image object.
364    Image_setNativeContext(env, image, buffer, fenceFd);
365}
366
367static void ImageWriter_close(JNIEnv* env, jobject thiz, jlong nativeCtx) {
368    ALOGV("%s:", __FUNCTION__);
369    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
370    if (ctx == NULL || thiz == NULL) {
371        // ImageWriter is already closed.
372        return;
373    }
374
375    ANativeWindow* producer = ctx->getProducer();
376    if (producer != NULL) {
377        /**
378         * NATIVE_WINDOW_API_CPU isn't a good choice here, as it makes the bufferQueue not
379         * connectable after disconnect. MEDIA or CAMERA are treated the same internally.
380         * The producer listener will be cleared after disconnect call.
381         */
382        status_t res = native_window_api_disconnect(producer, /*api*/NATIVE_WINDOW_API_CAMERA);
383        /**
384         * This is not an error. if client calling process dies, the window will
385         * also die and all calls to it will return DEAD_OBJECT, thus it's already
386         * "disconnected"
387         */
388        if (res == DEAD_OBJECT) {
389            ALOGW("%s: While disconnecting ImageWriter from native window, the"
390                    " native window died already", __FUNCTION__);
391        } else if (res != OK) {
392            ALOGE("%s: native window disconnect failed: %s (%d)",
393                    __FUNCTION__, strerror(-res), res);
394            jniThrowRuntimeException(env, "Native window disconnect failed");
395            return;
396        }
397    }
398
399    ctx->decStrong((void*)ImageWriter_init);
400}
401
402static void ImageWriter_cancelImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image) {
403    ALOGV("%s", __FUNCTION__);
404    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
405    if (ctx == NULL || thiz == NULL) {
406        ALOGW("ImageWriter#close called before Image#close, consider calling Image#close first");
407        return;
408    }
409
410    sp<ANativeWindow> anw = ctx->getProducer();
411
412    GraphicBuffer *buffer = NULL;
413    int fenceFd = -1;
414    Image_getNativeContext(env, image, &buffer, &fenceFd);
415    if (buffer == NULL) {
416        // Cancel an already cancelled image is harmless.
417        return;
418    }
419
420    // Unlock the image if it was locked
421    Image_unlockIfLocked(env, image);
422
423    anw->cancelBuffer(anw.get(), buffer, fenceFd);
424
425    Image_setNativeContext(env, image, NULL, -1);
426}
427
428static void ImageWriter_queueImage(JNIEnv* env, jobject thiz, jlong nativeCtx, jobject image,
429        jlong timestampNs, jint left, jint top, jint right, jint bottom) {
430    ALOGV("%s", __FUNCTION__);
431    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
432    if (ctx == NULL || thiz == NULL) {
433        jniThrowException(env, "java/lang/IllegalStateException",
434                "ImageWriterContext is not initialized");
435        return;
436    }
437
438    status_t res = OK;
439    sp<ANativeWindow> anw = ctx->getProducer();
440
441    GraphicBuffer *buffer = NULL;
442    int fenceFd = -1;
443    Image_getNativeContext(env, image, &buffer, &fenceFd);
444    if (buffer == NULL) {
445        jniThrowException(env, "java/lang/IllegalStateException",
446                "Image is not initialized");
447        return;
448    }
449
450    // Unlock image if it was locked.
451    Image_unlockIfLocked(env, image);
452
453    // Set timestamp
454    ALOGV("timestamp to be queued: %" PRId64, timestampNs);
455    res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
456    if (res != OK) {
457        jniThrowRuntimeException(env, "Set timestamp failed");
458        return;
459    }
460
461    // Set crop
462    android_native_rect_t cropRect;
463    cropRect.left = left;
464    cropRect.top = top;
465    cropRect.right = right;
466    cropRect.bottom = bottom;
467    res = native_window_set_crop(anw.get(), &cropRect);
468    if (res != OK) {
469        jniThrowRuntimeException(env, "Set crop rect failed");
470        return;
471    }
472
473    // Finally, queue input buffer
474    res = anw->queueBuffer(anw.get(), buffer, fenceFd);
475    if (res != OK) {
476        ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
477        switch (res) {
478            case NO_INIT:
479                jniThrowException(env, "java/lang/IllegalStateException",
480                    "Surface has been abandoned");
481                break;
482            default:
483                // TODO: handle other error cases here.
484                jniThrowRuntimeException(env, "Queue input buffer failed");
485        }
486        return;
487    }
488
489    // Clear the image native context: end of this image's lifecycle in public API.
490    Image_setNativeContext(env, image, NULL, -1);
491}
492
493static jint ImageWriter_attachAndQueueImage(JNIEnv* env, jobject thiz, jlong nativeCtx,
494        jlong nativeBuffer, jint imageFormat, jlong timestampNs, jint left, jint top,
495        jint right, jint bottom) {
496    ALOGV("%s", __FUNCTION__);
497    JNIImageWriterContext* const ctx = reinterpret_cast<JNIImageWriterContext *>(nativeCtx);
498    if (ctx == NULL || thiz == NULL) {
499        jniThrowException(env, "java/lang/IllegalStateException",
500                "ImageWriterContext is not initialized");
501        return -1;
502    }
503
504    sp<Surface> surface = ctx->getProducer();
505    status_t res = OK;
506    if (!isFormatOpaque(imageFormat)) {
507        // TODO: need implement, see b/19962027
508        jniThrowRuntimeException(env,
509                "nativeAttachImage for non-opaque image is not implement yet!!!");
510        return -1;
511    }
512
513    if (!isFormatOpaque(ctx->getBufferFormat())) {
514        jniThrowException(env, "java/lang/IllegalStateException",
515                "Trying to attach an opaque image into a non-opaque ImageWriter");
516        return -1;
517    }
518
519    // Image is guaranteed to be from ImageReader at this point, so it is safe to
520    // cast to BufferItem pointer.
521    BufferItem* opaqueBuffer = reinterpret_cast<BufferItem*>(nativeBuffer);
522    if (opaqueBuffer == NULL) {
523        jniThrowException(env, "java/lang/IllegalStateException",
524                "Image is not initialized or already closed");
525        return -1;
526    }
527
528    // Step 1. Attach Image
529    res = surface->attachBuffer(opaqueBuffer->mGraphicBuffer.get());
530    if (res != OK) {
531        ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
532        switch (res) {
533            case NO_INIT:
534                jniThrowException(env, "java/lang/IllegalStateException",
535                    "Surface has been abandoned");
536                break;
537            default:
538                // TODO: handle other error cases here.
539                jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
540        }
541        return res;
542    }
543    sp < ANativeWindow > anw = surface;
544
545    // Step 2. Set timestamp and crop. Note that we do not need unlock the image because
546    // it was not locked.
547    ALOGV("timestamp to be queued: %" PRId64, timestampNs);
548    res = native_window_set_buffers_timestamp(anw.get(), timestampNs);
549    if (res != OK) {
550        jniThrowRuntimeException(env, "Set timestamp failed");
551        return res;
552    }
553
554    android_native_rect_t cropRect;
555    cropRect.left = left;
556    cropRect.top = top;
557    cropRect.right = right;
558    cropRect.bottom = bottom;
559    res = native_window_set_crop(anw.get(), &cropRect);
560    if (res != OK) {
561        jniThrowRuntimeException(env, "Set crop rect failed");
562        return res;
563    }
564
565    // Step 3. Queue Image.
566    res = anw->queueBuffer(anw.get(), opaqueBuffer->mGraphicBuffer.get(), /*fenceFd*/
567            -1);
568    if (res != OK) {
569        ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
570        switch (res) {
571            case NO_INIT:
572                jniThrowException(env, "java/lang/IllegalStateException",
573                    "Surface has been abandoned");
574                break;
575            default:
576                // TODO: handle other error cases here.
577                jniThrowRuntimeException(env, "Queue input buffer failed");
578        }
579        return res;
580    }
581
582    // Do not set the image native context. Since it would overwrite the existing native context
583    // of the image that is from ImageReader, the subsequent image close will run into issues.
584
585    return res;
586}
587
588// --------------------------Image methods---------------------------------------
589
590static void Image_getNativeContext(JNIEnv* env, jobject thiz,
591        GraphicBuffer** buffer, int* fenceFd) {
592    ALOGV("%s", __FUNCTION__);
593    if (buffer != NULL) {
594        GraphicBuffer *gb = reinterpret_cast<GraphicBuffer *>
595                  (env->GetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer));
596        *buffer = gb;
597    }
598
599    if (fenceFd != NULL) {
600        *fenceFd = reinterpret_cast<jint>(env->GetIntField(
601                thiz, gSurfaceImageClassInfo.mNativeFenceFd));
602    }
603}
604
605static void Image_setNativeContext(JNIEnv* env, jobject thiz,
606        sp<GraphicBuffer> buffer, int fenceFd) {
607    ALOGV("%s:", __FUNCTION__);
608    GraphicBuffer* p = NULL;
609    Image_getNativeContext(env, thiz, &p, /*fenceFd*/NULL);
610    if (buffer != 0) {
611        buffer->incStrong((void*)Image_setNativeContext);
612    }
613    if (p) {
614        p->decStrong((void*)Image_setNativeContext);
615    }
616    env->SetLongField(thiz, gSurfaceImageClassInfo.mNativeBuffer,
617            reinterpret_cast<jlong>(buffer.get()));
618
619    env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
620}
621
622static void Image_unlockIfLocked(JNIEnv* env, jobject thiz) {
623    ALOGV("%s", __FUNCTION__);
624    GraphicBuffer* buffer;
625    Image_getNativeContext(env, thiz, &buffer, NULL);
626    if (buffer == NULL) {
627        jniThrowException(env, "java/lang/IllegalStateException",
628                "Image is not initialized");
629        return;
630    }
631
632    // Is locked?
633    bool isLocked = false;
634    jobject planes = NULL;
635    if (!isFormatOpaque(buffer->getPixelFormat())) {
636        planes = env->GetObjectField(thiz, gSurfaceImageClassInfo.mPlanes);
637    }
638    isLocked = (planes != NULL);
639    if (isLocked) {
640        // no need to use fence here, as we it will be consumed by either cancel or queue buffer.
641        status_t res = buffer->unlock();
642        if (res != OK) {
643            jniThrowRuntimeException(env, "unlock buffer failed");
644        }
645        ALOGV("Successfully unlocked the image");
646    }
647}
648
649static jint Image_getWidth(JNIEnv* env, jobject thiz) {
650    ALOGV("%s", __FUNCTION__);
651    GraphicBuffer* buffer;
652    Image_getNativeContext(env, thiz, &buffer, NULL);
653    if (buffer == NULL) {
654        jniThrowException(env, "java/lang/IllegalStateException",
655                "Image is not initialized");
656        return -1;
657    }
658
659    return buffer->getWidth();
660}
661
662static jint Image_getHeight(JNIEnv* env, jobject thiz) {
663    ALOGV("%s", __FUNCTION__);
664    GraphicBuffer* buffer;
665    Image_getNativeContext(env, thiz, &buffer, NULL);
666    if (buffer == NULL) {
667        jniThrowException(env, "java/lang/IllegalStateException",
668                "Image is not initialized");
669        return -1;
670    }
671
672    return buffer->getHeight();
673}
674
675// Some formats like JPEG defined with different values between android.graphics.ImageFormat and
676// graphics.h, need convert to the one defined in graphics.h here.
677static int Image_getPixelFormat(JNIEnv* env, int format) {
678    int jpegFormat;
679    jfieldID fid;
680
681    ALOGV("%s: format = 0x%x", __FUNCTION__, format);
682
683    jclass imageFormatClazz = env->FindClass("android/graphics/ImageFormat");
684    ALOG_ASSERT(imageFormatClazz != NULL);
685
686    fid = env->GetStaticFieldID(imageFormatClazz, "JPEG", "I");
687    jpegFormat = env->GetStaticIntField(imageFormatClazz, fid);
688
689    // Translate the JPEG to BLOB for camera purpose.
690    if (format == jpegFormat) {
691        format = HAL_PIXEL_FORMAT_BLOB;
692    }
693
694    return format;
695}
696
697static jint Image_getFormat(JNIEnv* env, jobject thiz) {
698    ALOGV("%s", __FUNCTION__);
699    GraphicBuffer* buffer;
700    Image_getNativeContext(env, thiz, &buffer, NULL);
701    if (buffer == NULL) {
702        jniThrowException(env, "java/lang/IllegalStateException",
703                "Image is not initialized");
704        return 0;
705    }
706
707    return Image_getPixelFormat(env, buffer->getPixelFormat());
708}
709
710static void Image_setFenceFd(JNIEnv* env, jobject thiz, int fenceFd) {
711    ALOGV("%s:", __FUNCTION__);
712    env->SetIntField(thiz, gSurfaceImageClassInfo.mNativeFenceFd, reinterpret_cast<jint>(fenceFd));
713}
714
715static void Image_getLockedImage(JNIEnv* env, jobject thiz, LockedImage *image) {
716    ALOGV("%s", __FUNCTION__);
717    GraphicBuffer* buffer;
718    int fenceFd = -1;
719    Image_getNativeContext(env, thiz, &buffer, &fenceFd);
720    if (buffer == NULL) {
721        jniThrowException(env, "java/lang/IllegalStateException",
722                "Image is not initialized");
723        return;
724    }
725
726    void* pData = NULL;
727    android_ycbcr ycbcr = android_ycbcr();
728    status_t res;
729    int format = Image_getFormat(env, thiz);
730    int flexFormat = format;
731    if (isPossiblyYUV(format)) {
732        // ImageWriter doesn't use crop by itself, app sets it, use the no crop version.
733        res = buffer->lockAsyncYCbCr(GRALLOC_USAGE_SW_WRITE_OFTEN, &ycbcr, fenceFd);
734        // Clear the fenceFd as it is already consumed by lock call.
735        Image_setFenceFd(env, thiz, /*fenceFd*/-1);
736        if (res != OK) {
737            jniThrowRuntimeException(env, "lockAsyncYCbCr failed for YUV buffer");
738            return;
739        }
740        pData = ycbcr.y;
741        flexFormat = HAL_PIXEL_FORMAT_YCbCr_420_888;
742    }
743
744    // lockAsyncYCbCr for YUV is unsuccessful.
745    if (pData == NULL) {
746        res = buffer->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &pData, fenceFd);
747        if (res != OK) {
748            jniThrowRuntimeException(env, "lockAsync failed");
749            return;
750        }
751    }
752
753    image->data = reinterpret_cast<uint8_t*>(pData);
754    image->width = buffer->getWidth();
755    image->height = buffer->getHeight();
756    image->format = format;
757    image->flexFormat = flexFormat;
758    image->stride = (ycbcr.y != NULL) ? static_cast<uint32_t>(ycbcr.ystride) : buffer->getStride();
759
760    image->dataCb = reinterpret_cast<uint8_t*>(ycbcr.cb);
761    image->dataCr = reinterpret_cast<uint8_t*>(ycbcr.cr);
762    image->chromaStride = static_cast<uint32_t>(ycbcr.cstride);
763    image->chromaStep = static_cast<uint32_t>(ycbcr.chroma_step);
764    ALOGV("Successfully locked the image");
765    // crop, transform, scalingMode, timestamp, and frameNumber should be set by producer,
766    // and we don't set them here.
767}
768
769static bool usingRGBAToJpegOverride(int32_t bufferFormat, int32_t writerCtxFormat) {
770    return writerCtxFormat == HAL_PIXEL_FORMAT_BLOB && bufferFormat == HAL_PIXEL_FORMAT_RGBA_8888;
771}
772
773static int32_t applyFormatOverrides(int32_t bufferFormat, int32_t writerCtxFormat)
774{
775    // Using HAL_PIXEL_FORMAT_RGBA_8888 gralloc buffers containing JPEGs to get around SW
776    // write limitations for some platforms (b/17379185).
777    if (usingRGBAToJpegOverride(bufferFormat, writerCtxFormat)) {
778        return HAL_PIXEL_FORMAT_BLOB;
779    }
780    return bufferFormat;
781}
782
783static uint32_t Image_getJpegSize(LockedImage* buffer, bool usingRGBAOverride) {
784    ALOGV("%s", __FUNCTION__);
785    ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
786    uint32_t size = 0;
787    uint32_t width = buffer->width;
788    uint8_t* jpegBuffer = buffer->data;
789
790    if (usingRGBAOverride) {
791        width = (buffer->width + buffer->stride * (buffer->height - 1)) * 4;
792    }
793
794    // First check for JPEG transport header at the end of the buffer
795    uint8_t* header = jpegBuffer + (width - sizeof(struct camera3_jpeg_blob));
796    struct camera3_jpeg_blob *blob = (struct camera3_jpeg_blob*)(header);
797    if (blob->jpeg_blob_id == CAMERA3_JPEG_BLOB_ID) {
798        size = blob->jpeg_size;
799        ALOGV("%s: Jpeg size = %d", __FUNCTION__, size);
800    }
801
802    // failed to find size, default to whole buffer
803    if (size == 0) {
804        /*
805         * This is a problem because not including the JPEG header
806         * means that in certain rare situations a regular JPEG blob
807         * will be misidentified as having a header, in which case
808         * we will get a garbage size value.
809         */
810        ALOGW("%s: No JPEG header detected, defaulting to size=width=%d",
811                __FUNCTION__, width);
812        size = width;
813    }
814
815    return size;
816}
817
818static void Image_getLockedImageInfo(JNIEnv* env, LockedImage* buffer, int idx,
819        int32_t writerFormat, uint8_t **base, uint32_t *size, int *pixelStride, int *rowStride) {
820    ALOGV("%s", __FUNCTION__);
821    ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
822    ALOG_ASSERT(base != NULL, "base is NULL!!!");
823    ALOG_ASSERT(size != NULL, "size is NULL!!!");
824    ALOG_ASSERT(pixelStride != NULL, "pixelStride is NULL!!!");
825    ALOG_ASSERT(rowStride != NULL, "rowStride is NULL!!!");
826    ALOG_ASSERT((idx < IMAGE_WRITER_MAX_NUM_PLANES) && (idx >= 0));
827
828    ALOGV("%s: buffer: %p", __FUNCTION__, buffer);
829
830    uint32_t dataSize, ySize, cSize, cStride;
831    uint32_t pStride = 0, rStride = 0;
832    uint8_t *cb, *cr;
833    uint8_t *pData = NULL;
834    int bytesPerPixel = 0;
835
836    dataSize = ySize = cSize = cStride = 0;
837    int32_t fmt = buffer->flexFormat;
838
839    bool usingRGBAOverride = usingRGBAToJpegOverride(fmt, writerFormat);
840    fmt = applyFormatOverrides(fmt, writerFormat);
841    switch (fmt) {
842        case HAL_PIXEL_FORMAT_YCbCr_420_888:
843            pData =
844                (idx == 0) ?
845                    buffer->data :
846                (idx == 1) ?
847                    buffer->dataCb :
848                buffer->dataCr;
849            // only map until last pixel
850            if (idx == 0) {
851                pStride = 1;
852                rStride = buffer->stride;
853                dataSize = buffer->stride * (buffer->height - 1) + buffer->width;
854            } else {
855                pStride = buffer->chromaStep;
856                rStride = buffer->chromaStride;
857                dataSize = buffer->chromaStride * (buffer->height / 2 - 1) +
858                        buffer->chromaStep * (buffer->width / 2 - 1) + 1;
859            }
860            break;
861        // NV21
862        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
863            cr = buffer->data + (buffer->stride * buffer->height);
864            cb = cr + 1;
865            // only map until last pixel
866            ySize = buffer->width * (buffer->height - 1) + buffer->width;
867            cSize = buffer->width * (buffer->height / 2 - 1) + buffer->width - 1;
868
869            pData =
870                (idx == 0) ?
871                    buffer->data :
872                (idx == 1) ?
873                    cb:
874                cr;
875
876            dataSize = (idx == 0) ? ySize : cSize;
877            pStride = (idx == 0) ? 1 : 2;
878            rStride = buffer->width;
879            break;
880        case HAL_PIXEL_FORMAT_YV12:
881            // Y and C stride need to be 16 pixel aligned.
882            LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
883                                "Stride is not 16 pixel aligned %d", buffer->stride);
884
885            ySize = buffer->stride * buffer->height;
886            cStride = ALIGN(buffer->stride / 2, 16);
887            cr = buffer->data + ySize;
888            cSize = cStride * buffer->height / 2;
889            cb = cr + cSize;
890
891            pData =
892                (idx == 0) ?
893                    buffer->data :
894                (idx == 1) ?
895                    cb :
896                cr;
897            dataSize = (idx == 0) ? ySize : cSize;
898            pStride = 1;
899            rStride = (idx == 0) ? buffer->stride : ALIGN(buffer->stride / 2, 16);
900            break;
901        case HAL_PIXEL_FORMAT_Y8:
902            // Single plane, 8bpp.
903            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
904
905            pData = buffer->data;
906            dataSize = buffer->stride * buffer->height;
907            pStride = 1;
908            rStride = buffer->stride;
909            break;
910        case HAL_PIXEL_FORMAT_Y16:
911            bytesPerPixel = 2;
912            // Single plane, 16bpp, strides are specified in pixels, not in bytes
913            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
914
915            pData = buffer->data;
916            dataSize = buffer->stride * buffer->height * bytesPerPixel;
917            pStride = bytesPerPixel;
918            rStride = buffer->stride * 2;
919            break;
920        case HAL_PIXEL_FORMAT_BLOB:
921            // Used for JPEG data, height must be 1, width == size, single plane.
922            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
923            ALOG_ASSERT(buffer->height == 1, "JPEG should has height value %d", buffer->height);
924
925            pData = buffer->data;
926            dataSize = Image_getJpegSize(buffer, usingRGBAOverride);
927            pStride = bytesPerPixel;
928            rowStride = 0;
929            break;
930        case HAL_PIXEL_FORMAT_RAW16:
931            // Single plane 16bpp bayer data.
932            bytesPerPixel = 2;
933            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
934            pData = buffer->data;
935            dataSize = buffer->stride * buffer->height * bytesPerPixel;
936            pStride = bytesPerPixel;
937            rStride = buffer->stride * 2;
938            break;
939        case HAL_PIXEL_FORMAT_RAW10:
940            // Single plane 10bpp bayer data.
941            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
942            LOG_ALWAYS_FATAL_IF(buffer->width % 4,
943                                "Width is not multiple of 4 %d", buffer->width);
944            LOG_ALWAYS_FATAL_IF(buffer->height % 2,
945                                "Height is not even %d", buffer->height);
946            LOG_ALWAYS_FATAL_IF(buffer->stride < (buffer->width * 10 / 8),
947                                "stride (%d) should be at least %d",
948                                buffer->stride, buffer->width * 10 / 8);
949            pData = buffer->data;
950            dataSize = buffer->stride * buffer->height;
951            pStride = 0;
952            rStride = buffer->stride;
953            break;
954        case HAL_PIXEL_FORMAT_RGBA_8888:
955        case HAL_PIXEL_FORMAT_RGBX_8888:
956            // Single plane, 32bpp.
957            bytesPerPixel = 4;
958            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
959            pData = buffer->data;
960            dataSize = buffer->stride * buffer->height * bytesPerPixel;
961            pStride = bytesPerPixel;
962            rStride = buffer->stride * 4;
963            break;
964        case HAL_PIXEL_FORMAT_RGB_565:
965            // Single plane, 16bpp.
966            bytesPerPixel = 2;
967            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
968            pData = buffer->data;
969            dataSize = buffer->stride * buffer->height * bytesPerPixel;
970            pStride = bytesPerPixel;
971            rStride = buffer->stride * 2;
972            break;
973        case HAL_PIXEL_FORMAT_RGB_888:
974            // Single plane, 24bpp.
975            bytesPerPixel = 3;
976            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
977            pData = buffer->data;
978            dataSize = buffer->stride * buffer->height * bytesPerPixel;
979            pStride = bytesPerPixel;
980            rStride = buffer->stride * 3;
981            break;
982        default:
983            jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
984                                 "Pixel format: 0x%x is unsupported", fmt);
985            break;
986    }
987
988    *base = pData;
989    *size = dataSize;
990    *pixelStride = pStride;
991    *rowStride = rStride;
992}
993
994static jobjectArray Image_createSurfacePlanes(JNIEnv* env, jobject thiz,
995        int numPlanes, int writerFormat) {
996    ALOGV("%s: create SurfacePlane array with size %d", __FUNCTION__, numPlanes);
997    int rowStride, pixelStride;
998    uint8_t *pData;
999    uint32_t dataSize;
1000    jobject byteBuffer;
1001
1002    int format = Image_getFormat(env, thiz);
1003    if (isFormatOpaque(format) && numPlanes > 0) {
1004        String8 msg;
1005        msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
1006                " must be 0", format, numPlanes);
1007        jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
1008        return NULL;
1009    }
1010
1011    jobjectArray surfacePlanes = env->NewObjectArray(numPlanes, gSurfacePlaneClassInfo.clazz,
1012            /*initial_element*/NULL);
1013    if (surfacePlanes == NULL) {
1014        jniThrowRuntimeException(env, "Failed to create SurfacePlane arrays,"
1015                " probably out of memory");
1016        return NULL;
1017    }
1018    if (isFormatOpaque(format)) {
1019        return surfacePlanes;
1020    }
1021
1022    // Buildup buffer info: rowStride, pixelStride and byteBuffers.
1023    LockedImage lockedImg = LockedImage();
1024    Image_getLockedImage(env, thiz, &lockedImg);
1025
1026    // Create all SurfacePlanes
1027    writerFormat = Image_getPixelFormat(env, writerFormat);
1028    for (int i = 0; i < numPlanes; i++) {
1029        Image_getLockedImageInfo(env, &lockedImg, i, writerFormat,
1030                &pData, &dataSize, &pixelStride, &rowStride);
1031        byteBuffer = env->NewDirectByteBuffer(pData, dataSize);
1032        if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
1033            jniThrowException(env, "java/lang/IllegalStateException",
1034                    "Failed to allocate ByteBuffer");
1035            return NULL;
1036        }
1037
1038        // Finally, create this SurfacePlane.
1039        jobject surfacePlane = env->NewObject(gSurfacePlaneClassInfo.clazz,
1040                    gSurfacePlaneClassInfo.ctor, thiz, rowStride, pixelStride, byteBuffer);
1041        env->SetObjectArrayElement(surfacePlanes, i, surfacePlane);
1042    }
1043
1044    return surfacePlanes;
1045}
1046
1047// -------------------------------Private convenience methods--------------------
1048
1049static bool isFormatOpaque(int format) {
1050    // Only treat IMPLEMENTATION_DEFINED as an opaque format for now.
1051    return format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
1052}
1053
1054static bool isPossiblyYUV(PixelFormat format) {
1055    switch (static_cast<int>(format)) {
1056        case HAL_PIXEL_FORMAT_RGBA_8888:
1057        case HAL_PIXEL_FORMAT_RGBX_8888:
1058        case HAL_PIXEL_FORMAT_RGB_888:
1059        case HAL_PIXEL_FORMAT_RGB_565:
1060        case HAL_PIXEL_FORMAT_BGRA_8888:
1061        case HAL_PIXEL_FORMAT_Y8:
1062        case HAL_PIXEL_FORMAT_Y16:
1063        case HAL_PIXEL_FORMAT_RAW16:
1064        case HAL_PIXEL_FORMAT_RAW10:
1065        case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1066        case HAL_PIXEL_FORMAT_BLOB:
1067        case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1068            return false;
1069
1070        case HAL_PIXEL_FORMAT_YV12:
1071        case HAL_PIXEL_FORMAT_YCbCr_420_888:
1072        case HAL_PIXEL_FORMAT_YCbCr_422_SP:
1073        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
1074        case HAL_PIXEL_FORMAT_YCbCr_422_I:
1075        default:
1076            return true;
1077    }
1078}
1079
1080} // extern "C"
1081
1082// ----------------------------------------------------------------------------
1083
1084static JNINativeMethod gImageWriterMethods[] = {
1085    {"nativeClassInit",         "()V",                        (void*)ImageWriter_classInit },
1086    {"nativeInit",              "(Ljava/lang/Object;Landroid/view/Surface;I)J",
1087                                                              (void*)ImageWriter_init },
1088    {"nativeClose",              "(J)V",                      (void*)ImageWriter_close },
1089    {"nativeAttachAndQueueImage", "(JJIJIIII)I",          (void*)ImageWriter_attachAndQueueImage },
1090    {"nativeDequeueInputImage", "(JLandroid/media/Image;)V",  (void*)ImageWriter_dequeueImage },
1091    {"nativeQueueInputImage",   "(JLandroid/media/Image;JIIII)V",  (void*)ImageWriter_queueImage },
1092    {"cancelImage",             "(JLandroid/media/Image;)V",   (void*)ImageWriter_cancelImage },
1093};
1094
1095static JNINativeMethod gImageMethods[] = {
1096    {"nativeCreatePlanes",      "(II)[Landroid/media/ImageWriter$WriterSurfaceImage$SurfacePlane;",
1097                                                              (void*)Image_createSurfacePlanes },
1098    {"nativeGetWidth",         "()I",                         (void*)Image_getWidth },
1099    {"nativeGetHeight",        "()I",                         (void*)Image_getHeight },
1100    {"nativeGetFormat",        "()I",                         (void*)Image_getFormat },
1101};
1102
1103int register_android_media_ImageWriter(JNIEnv *env) {
1104
1105    int ret1 = AndroidRuntime::registerNativeMethods(env,
1106                   "android/media/ImageWriter", gImageWriterMethods, NELEM(gImageWriterMethods));
1107
1108    int ret2 = AndroidRuntime::registerNativeMethods(env,
1109                   "android/media/ImageWriter$WriterSurfaceImage", gImageMethods, NELEM(gImageMethods));
1110
1111    return (ret1 || ret2);
1112}
1113
1114