android_media_ImageReader.cpp revision ef961215599b1c154130d4e64e46a401d6bfef67
1/*
2 * Copyright 2013 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 "ImageReader_JNI"
19#include <utils/Log.h>
20#include <utils/misc.h>
21#include <utils/List.h>
22#include <utils/String8.h>
23
24#include <cstdio>
25
26#include <gui/CpuConsumer.h>
27#include <gui/Surface.h>
28#include <camera3.h>
29
30#include <android_runtime/AndroidRuntime.h>
31#include <android_runtime/android_view_Surface.h>
32
33#include <jni.h>
34#include <JNIHelp.h>
35
36#define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
37
38#define ANDROID_MEDIA_IMAGEREADER_JNI_ID           "mCpuConsumer"
39#define ANDROID_MEDIA_IMAGEREADER_CTX_JNI_ID       "mNativeContext"
40#define ANDROID_MEDIA_SURFACEIMAGE_BUFFER_JNI_ID   "mLockedBuffer"
41#define ANDROID_MEDIA_SURFACEIMAGE_TS_JNI_ID       "mTimestamp"
42
43// ----------------------------------------------------------------------------
44
45using namespace android;
46
47enum {
48    IMAGE_READER_MAX_NUM_PLANES = 3,
49};
50
51static struct {
52    jfieldID mNativeContext;
53    jmethodID postEventFromNative;
54} gImageReaderClassInfo;
55
56static struct {
57    jfieldID mLockedBuffer;
58    jfieldID mTimestamp;
59} gSurfaceImageClassInfo;
60
61static struct {
62    jclass clazz;
63    jmethodID ctor;
64} gSurfacePlaneClassInfo;
65
66// ----------------------------------------------------------------------------
67
68class JNIImageReaderContext : public CpuConsumer::FrameAvailableListener
69{
70public:
71    JNIImageReaderContext(JNIEnv* env, jobject weakThiz, jclass clazz, int maxImages);
72
73    virtual ~JNIImageReaderContext();
74
75    virtual void onFrameAvailable();
76
77    CpuConsumer::LockedBuffer* getLockedBuffer();
78
79    void returnLockedBuffer(CpuConsumer::LockedBuffer* buffer);
80
81    CpuConsumer* getCpuConsumer() { return mConsumer.get(); }
82
83    void setCpuConsumer(sp<CpuConsumer> consumer) { mConsumer = consumer; }
84
85    void setBufferFormat(int format) { mFormat = format; }
86    int getBufferFormat() { return mFormat; }
87
88    void setBufferWidth(int width) { mWidth = width; }
89    int getBufferWidth() { return mWidth; }
90
91    void setBufferHeight(int height) { mHeight = height; }
92    int getBufferHeight() { return mHeight; }
93
94private:
95    static JNIEnv* getJNIEnv(bool* needsDetach);
96    static void detachJNI();
97
98    List<CpuConsumer::LockedBuffer*> mBuffers;
99    sp<CpuConsumer> mConsumer;
100    jobject mWeakThiz;
101    jclass mClazz;
102    int mFormat;
103    int mWidth;
104    int mHeight;
105};
106
107JNIImageReaderContext::JNIImageReaderContext(JNIEnv* env,
108        jobject weakThiz, jclass clazz, int maxImages) :
109    mWeakThiz(env->NewGlobalRef(weakThiz)),
110    mClazz((jclass)env->NewGlobalRef(clazz)) {
111    for (int i = 0; i < maxImages; i++) {
112        CpuConsumer::LockedBuffer *buffer = new CpuConsumer::LockedBuffer;
113        mBuffers.push_back(buffer);
114    }
115}
116
117JNIEnv* JNIImageReaderContext::getJNIEnv(bool* needsDetach) {
118    LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
119    *needsDetach = false;
120    JNIEnv* env = AndroidRuntime::getJNIEnv();
121    if (env == NULL) {
122        JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
123        JavaVM* vm = AndroidRuntime::getJavaVM();
124        int result = vm->AttachCurrentThread(&env, (void*) &args);
125        if (result != JNI_OK) {
126            ALOGE("thread attach failed: %#x", result);
127            return NULL;
128        }
129        *needsDetach = true;
130    }
131    return env;
132}
133
134void JNIImageReaderContext::detachJNI() {
135    JavaVM* vm = AndroidRuntime::getJavaVM();
136    int result = vm->DetachCurrentThread();
137    if (result != JNI_OK) {
138        ALOGE("thread detach failed: %#x", result);
139    }
140}
141
142CpuConsumer::LockedBuffer* JNIImageReaderContext::getLockedBuffer() {
143    if (mBuffers.empty()) {
144        return NULL;
145    }
146    // Return a LockedBuffer pointer and remove it from the list
147    List<CpuConsumer::LockedBuffer*>::iterator it = mBuffers.begin();
148    CpuConsumer::LockedBuffer* buffer = *it;
149    mBuffers.erase(it);
150    return buffer;
151}
152
153void JNIImageReaderContext::returnLockedBuffer(CpuConsumer::LockedBuffer * buffer) {
154    mBuffers.push_back(buffer);
155}
156
157JNIImageReaderContext::~JNIImageReaderContext() {
158    bool needsDetach = false;
159    JNIEnv* env = getJNIEnv(&needsDetach);
160    if (env != NULL) {
161        env->DeleteGlobalRef(mWeakThiz);
162        env->DeleteGlobalRef(mClazz);
163    } else {
164        ALOGW("leaking JNI object references");
165    }
166    if (needsDetach) {
167        detachJNI();
168    }
169
170    // Delete LockedBuffers
171    for (List<CpuConsumer::LockedBuffer *>::iterator it = mBuffers.begin();
172            it != mBuffers.end(); it++) {
173        delete *it;
174    }
175    mBuffers.clear();
176    mConsumer.clear();
177}
178
179void JNIImageReaderContext::onFrameAvailable()
180{
181    ALOGV("%s: frame available", __FUNCTION__);
182    bool needsDetach = false;
183    JNIEnv* env = getJNIEnv(&needsDetach);
184    if (env != NULL) {
185        env->CallStaticVoidMethod(mClazz, gImageReaderClassInfo.postEventFromNative, mWeakThiz);
186    } else {
187        ALOGW("onFrameAvailable event will not posted");
188    }
189    if (needsDetach) {
190        detachJNI();
191    }
192}
193
194// ----------------------------------------------------------------------------
195
196extern "C" {
197
198static JNIImageReaderContext* ImageReader_getContext(JNIEnv* env, jobject thiz)
199{
200    JNIImageReaderContext *ctx;
201    ctx = reinterpret_cast<JNIImageReaderContext *>
202              (env->GetLongField(thiz, gImageReaderClassInfo.mNativeContext));
203    return ctx;
204}
205
206static CpuConsumer* ImageReader_getCpuConsumer(JNIEnv* env, jobject thiz)
207{
208    ALOGV("%s:", __FUNCTION__);
209    JNIImageReaderContext* const ctx = ImageReader_getContext(env, thiz);
210    if (ctx == NULL) {
211        jniThrowRuntimeException(env, "ImageReaderContext is not initialized");
212        return NULL;
213    }
214    return ctx->getCpuConsumer();
215}
216
217static void ImageReader_setNativeContext(JNIEnv* env,
218        jobject thiz, sp<JNIImageReaderContext> ctx)
219{
220    ALOGV("%s:", __FUNCTION__);
221    JNIImageReaderContext* const p = ImageReader_getContext(env, thiz);
222    if (ctx != 0) {
223        ctx->incStrong((void*)ImageReader_setNativeContext);
224    }
225    if (p) {
226        p->decStrong((void*)ImageReader_setNativeContext);
227    }
228    env->SetLongField(thiz, gImageReaderClassInfo.mNativeContext,
229            reinterpret_cast<jlong>(ctx.get()));
230}
231
232static CpuConsumer::LockedBuffer* Image_getLockedBuffer(JNIEnv* env, jobject image)
233{
234    return reinterpret_cast<CpuConsumer::LockedBuffer*>(
235            env->GetLongField(image, gSurfaceImageClassInfo.mLockedBuffer));
236}
237
238static void Image_setBuffer(JNIEnv* env, jobject thiz,
239        const CpuConsumer::LockedBuffer* buffer)
240{
241    env->SetLongField(thiz, gSurfaceImageClassInfo.mLockedBuffer, reinterpret_cast<jlong>(buffer));
242}
243
244// Some formats like JPEG defined with different values between android.graphics.ImageFormat and
245// graphics.h, need convert to the one defined in graphics.h here.
246static int Image_getPixelFormat(JNIEnv* env, int format)
247{
248    int jpegFormat, rawSensorFormat;
249    jfieldID fid;
250
251    ALOGV("%s: format = 0x%x", __FUNCTION__, format);
252
253    jclass imageFormatClazz = env->FindClass("android/graphics/ImageFormat");
254    ALOG_ASSERT(imageFormatClazz != NULL);
255
256    fid = env->GetStaticFieldID(imageFormatClazz, "JPEG", "I");
257    jpegFormat = env->GetStaticIntField(imageFormatClazz, fid);
258    fid = env->GetStaticFieldID(imageFormatClazz, "RAW_SENSOR", "I");
259    rawSensorFormat = env->GetStaticIntField(imageFormatClazz, fid);
260
261    // Translate the JPEG to BLOB for camera purpose, an add more if more mismatch is found.
262    if (format == jpegFormat) {
263        format = HAL_PIXEL_FORMAT_BLOB;
264    }
265    // Same thing for RAW_SENSOR format
266    if (format == rawSensorFormat) {
267        format = HAL_PIXEL_FORMAT_RAW_SENSOR;
268    }
269
270    return format;
271}
272
273static uint32_t Image_getJpegSize(CpuConsumer::LockedBuffer* buffer)
274{
275    ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
276    uint32_t size = 0;
277    uint32_t width = buffer->width;
278    uint8_t* jpegBuffer = buffer->data;
279
280    // First check for JPEG transport header at the end of the buffer
281    uint8_t* header = jpegBuffer + (width - sizeof(struct camera3_jpeg_blob));
282    struct camera3_jpeg_blob *blob = (struct camera3_jpeg_blob*)(header);
283    if (blob->jpeg_blob_id == CAMERA3_JPEG_BLOB_ID) {
284        size = blob->jpeg_size;
285        ALOGV("%s: Jpeg size = %d", __FUNCTION__, size);
286    }
287
288    // failed to find size, default to whole buffer
289    if (size == 0) {
290        size = width;
291    }
292
293    return size;
294}
295
296static void Image_getLockedBufferInfo(JNIEnv* env, CpuConsumer::LockedBuffer* buffer, int idx,
297                                uint8_t **base, uint32_t *size)
298{
299    ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
300    ALOG_ASSERT(base != NULL, "base is NULL!!!");
301    ALOG_ASSERT(size != NULL, "size is NULL!!!");
302    ALOG_ASSERT((idx < IMAGE_READER_MAX_NUM_PLANES) && (idx >= 0));
303
304    ALOGV("%s: buffer: %p", __FUNCTION__, buffer);
305
306    uint32_t dataSize, ySize, cSize, cStride;
307    uint8_t *cb, *cr;
308    uint8_t *pData = NULL;
309
310    dataSize = ySize = cSize = cStride = 0;
311    int32_t fmt = buffer->format;
312    switch (fmt) {
313        case HAL_PIXEL_FORMAT_YCbCr_420_888:
314            pData =
315                (idx == 0) ?
316                    buffer->data :
317                (idx == 1) ?
318                    buffer->dataCb :
319                buffer->dataCr;
320            if (idx == 0) {
321                dataSize = buffer->stride * buffer->height;
322            } else {
323                dataSize = buffer->chromaStride * buffer->height / 2;
324            }
325            break;
326        // NV21
327        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
328            cr = buffer->data + (buffer->stride * buffer->height);
329            cb = cr + 1;
330            ySize = buffer->width * buffer->height;
331            cSize = buffer->width * buffer->height / 2;
332
333            pData =
334                (idx == 0) ?
335                    buffer->data :
336                (idx == 1) ?
337                    cb:
338                cr;
339
340            dataSize = (idx == 0) ? ySize : cSize;
341            break;
342        case HAL_PIXEL_FORMAT_YV12:
343            // Y and C stride need to be 16 pixel aligned.
344            LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
345                                "Stride is not 16 pixel aligned %d", buffer->stride);
346
347            ySize = buffer->stride * buffer->height;
348            cStride = ALIGN(buffer->stride / 2, 16);
349            cr = buffer->data + ySize;
350            cSize = cStride * buffer->height / 2;
351            cb = cr + cSize;
352
353            pData =
354                (idx == 0) ?
355                    buffer->data :
356                (idx == 1) ?
357                    cb :
358                cr;
359            dataSize = (idx == 0) ? ySize : cSize;
360            break;
361        case HAL_PIXEL_FORMAT_Y8:
362            // Single plane, 8bpp.
363            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
364
365            pData = buffer->data;
366            dataSize = buffer->stride * buffer->height;
367            break;
368        case HAL_PIXEL_FORMAT_Y16:
369            // Single plane, 16bpp, strides are specified in pixels, not in bytes
370            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
371
372            pData = buffer->data;
373            dataSize = buffer->stride * buffer->height * 2;
374            break;
375        case HAL_PIXEL_FORMAT_BLOB:
376            // Used for JPEG data, height must be 1, width == size, single plane.
377            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
378            ALOG_ASSERT(buffer->height == 1, "JPEG should has height value %d", buffer->height);
379
380            pData = buffer->data;
381            dataSize = Image_getJpegSize(buffer);
382            break;
383        case HAL_PIXEL_FORMAT_RAW_SENSOR:
384            // Single plane 16bpp bayer data.
385            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
386            pData = buffer->data;
387            dataSize = buffer->width * 2 * buffer->height;
388            break;
389        default:
390            jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
391                                 "Pixel format: 0x%x is unsupported", fmt);
392            break;
393    }
394
395    *base = pData;
396    *size = dataSize;
397}
398
399static jint Image_imageGetPixelStride(JNIEnv* env, CpuConsumer::LockedBuffer* buffer, int idx)
400{
401    ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
402    ALOG_ASSERT((idx < IMAGE_READER_MAX_NUM_PLANES) && (idx >= 0), "Index is out of range:%d", idx);
403
404    int pixelStride = 0;
405    ALOG_ASSERT(buffer != NULL, "buffer is NULL");
406
407    int32_t fmt = buffer->format;
408    switch (fmt) {
409        case HAL_PIXEL_FORMAT_YCbCr_420_888:
410            pixelStride = (idx == 0) ? 1 : buffer->chromaStep;
411            break;
412        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
413            pixelStride = (idx == 0) ? 1 : 2;
414            break;
415        case HAL_PIXEL_FORMAT_Y8:
416            // Single plane 8bpp data.
417            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
418            pixelStride;
419            break;
420        case HAL_PIXEL_FORMAT_YV12:
421            pixelStride = 1;
422            break;
423        case HAL_PIXEL_FORMAT_BLOB:
424            // Used for JPEG data, single plane, row and pixel strides are 0
425            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
426            pixelStride = 0;
427            break;
428        case HAL_PIXEL_FORMAT_Y16:
429        case HAL_PIXEL_FORMAT_RAW_SENSOR:
430            // Single plane 16bpp data.
431            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
432            pixelStride = 2;
433            break;
434        default:
435            jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
436                                 "Pixel format: 0x%x is unsupported", fmt);
437            break;
438    }
439
440    return pixelStride;
441}
442
443static jint Image_imageGetRowStride(JNIEnv* env, CpuConsumer::LockedBuffer* buffer, int idx)
444{
445    ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
446    ALOG_ASSERT((idx < IMAGE_READER_MAX_NUM_PLANES) && (idx >= 0));
447
448    int rowStride = 0;
449    ALOG_ASSERT(buffer != NULL, "buffer is NULL");
450
451    int32_t fmt = buffer->format;
452
453    switch (fmt) {
454        case HAL_PIXEL_FORMAT_YCbCr_420_888:
455            rowStride = (idx == 0) ? buffer->stride : buffer->chromaStride;
456            break;
457        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
458            rowStride = buffer->width;
459            break;
460        case HAL_PIXEL_FORMAT_YV12:
461            LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
462                                "Stride is not 16 pixel aligned %d", buffer->stride);
463            rowStride = (idx == 0) ? buffer->stride : ALIGN(buffer->stride / 2, 16);
464            break;
465        case HAL_PIXEL_FORMAT_BLOB:
466            // Used for JPEG data, single plane, row and pixel strides are 0
467            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
468            rowStride = 0;
469            break;
470        case HAL_PIXEL_FORMAT_Y8:
471            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
472            LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
473                                "Stride is not 16 pixel aligned %d", buffer->stride);
474            rowStride = buffer->stride;
475            break;
476        case HAL_PIXEL_FORMAT_Y16:
477        case HAL_PIXEL_FORMAT_RAW_SENSOR:
478            // In native side, strides are specified in pixels, not in bytes.
479            // Single plane 16bpp bayer data. even width/height,
480            // row stride multiple of 16 pixels (32 bytes)
481            ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
482            LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
483                                "Stride is not 16 pixel aligned %d", buffer->stride);
484            rowStride = buffer->stride * 2;
485            break;
486        default:
487            ALOGE("%s Pixel format: 0x%x is unsupported", __FUNCTION__, fmt);
488            jniThrowException(env, "java/lang/UnsupportedOperationException",
489                              "unsupported buffer format");
490          break;
491    }
492
493    return rowStride;
494}
495
496// ----------------------------------------------------------------------------
497
498static void ImageReader_classInit(JNIEnv* env, jclass clazz)
499{
500    ALOGV("%s:", __FUNCTION__);
501
502    jclass imageClazz = env->FindClass("android/media/ImageReader$SurfaceImage");
503    LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
504                        "can't find android/graphics/ImageReader$SurfaceImage");
505    gSurfaceImageClassInfo.mLockedBuffer = env->GetFieldID(
506            imageClazz, ANDROID_MEDIA_SURFACEIMAGE_BUFFER_JNI_ID, "J");
507    LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mLockedBuffer == NULL,
508                        "can't find android/graphics/ImageReader.%s",
509                        ANDROID_MEDIA_SURFACEIMAGE_BUFFER_JNI_ID);
510
511    gSurfaceImageClassInfo.mTimestamp = env->GetFieldID(
512            imageClazz, ANDROID_MEDIA_SURFACEIMAGE_TS_JNI_ID, "J");
513    LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mTimestamp == NULL,
514                        "can't find android/graphics/ImageReader.%s",
515                        ANDROID_MEDIA_SURFACEIMAGE_TS_JNI_ID);
516
517    gImageReaderClassInfo.mNativeContext = env->GetFieldID(
518            clazz, ANDROID_MEDIA_IMAGEREADER_CTX_JNI_ID, "J");
519    LOG_ALWAYS_FATAL_IF(gImageReaderClassInfo.mNativeContext == NULL,
520                        "can't find android/graphics/ImageReader.%s",
521                          ANDROID_MEDIA_IMAGEREADER_CTX_JNI_ID);
522
523    gImageReaderClassInfo.postEventFromNative = env->GetStaticMethodID(
524            clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
525    LOG_ALWAYS_FATAL_IF(gImageReaderClassInfo.postEventFromNative == NULL,
526                        "can't find android/graphics/ImageReader.postEventFromNative");
527
528    jclass planeClazz = env->FindClass("android/media/ImageReader$SurfaceImage$SurfacePlane");
529    LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
530    // FindClass only gives a local reference of jclass object.
531    gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
532    gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
533            "(Landroid/media/ImageReader$SurfaceImage;III)V");
534    LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
535            "Can not find SurfacePlane constructor");
536}
537
538static void ImageReader_init(JNIEnv* env, jobject thiz, jobject weakThiz,
539                             jint width, jint height, jint format, jint maxImages)
540{
541    status_t res;
542    int nativeFormat;
543
544    ALOGV("%s: width:%d, height: %d, format: 0x%x, maxImages:%d",
545          __FUNCTION__, width, height, format, maxImages);
546
547    nativeFormat = Image_getPixelFormat(env, format);
548
549    sp<BufferQueue> bq = new BufferQueue();
550    sp<CpuConsumer> consumer = new CpuConsumer(bq, true, maxImages);
551    // TODO: throw dvm exOutOfMemoryError?
552    if (consumer == NULL) {
553        jniThrowRuntimeException(env, "Failed to allocate native CpuConsumer");
554        return;
555    }
556
557    jclass clazz = env->GetObjectClass(thiz);
558    if (clazz == NULL) {
559        jniThrowRuntimeException(env, "Can't find android/graphics/ImageReader");
560        return;
561    }
562    sp<JNIImageReaderContext> ctx(new JNIImageReaderContext(env, weakThiz, clazz, maxImages));
563    ctx->setCpuConsumer(consumer);
564    consumer->setFrameAvailableListener(ctx);
565    ImageReader_setNativeContext(env, thiz, ctx);
566    ctx->setBufferFormat(nativeFormat);
567    ctx->setBufferWidth(width);
568    ctx->setBufferHeight(height);
569
570    // Set the width/height/format to the CpuConsumer
571    res = consumer->setDefaultBufferSize(width, height);
572    if (res != OK) {
573        jniThrowException(env, "java/lang/IllegalStateException",
574                          "Failed to set CpuConsumer buffer size");
575        return;
576    }
577    res = consumer->setDefaultBufferFormat(nativeFormat);
578    if (res != OK) {
579        jniThrowException(env, "java/lang/IllegalStateException",
580                          "Failed to set CpuConsumer buffer format");
581    }
582}
583
584static void ImageReader_close(JNIEnv* env, jobject thiz)
585{
586    ALOGV("%s:", __FUNCTION__);
587
588    JNIImageReaderContext* const ctx = ImageReader_getContext(env, thiz);
589    if (ctx == NULL) {
590        // ImageReader is already closed.
591        return;
592    }
593
594    CpuConsumer* consumer = ImageReader_getCpuConsumer(env, thiz);
595    if (consumer != NULL) {
596        consumer->abandon();
597        consumer->setFrameAvailableListener(NULL);
598    }
599    ImageReader_setNativeContext(env, thiz, NULL);
600}
601
602static void ImageReader_imageRelease(JNIEnv* env, jobject thiz, jobject image)
603{
604    ALOGV("%s:", __FUNCTION__);
605    JNIImageReaderContext* ctx = ImageReader_getContext(env, thiz);
606    if (ctx == NULL) {
607        ALOGW("ImageReader#close called before Image#close, consider calling Image#close first");
608        return;
609    }
610
611    CpuConsumer* consumer = ctx->getCpuConsumer();
612    CpuConsumer::LockedBuffer* buffer = Image_getLockedBuffer(env, image);
613    if (!buffer) {
614        ALOGW("Image already released!!!");
615        return;
616    }
617    consumer->unlockBuffer(*buffer);
618    Image_setBuffer(env, image, NULL);
619    ctx->returnLockedBuffer(buffer);
620}
621
622static jboolean ImageReader_imageSetup(JNIEnv* env, jobject thiz,
623                                             jobject image)
624{
625    ALOGV("%s:", __FUNCTION__);
626    JNIImageReaderContext* ctx = ImageReader_getContext(env, thiz);
627    if (ctx == NULL) {
628        jniThrowRuntimeException(env, "ImageReaderContext is not initialized");
629        return false;
630    }
631
632    CpuConsumer* consumer = ctx->getCpuConsumer();
633    CpuConsumer::LockedBuffer* buffer = ctx->getLockedBuffer();
634    if (buffer == NULL) {
635        ALOGE("Unable to acquire a lockedBuffer, very likely client tries to lock more than"
636            "maxImages buffers");
637        return false;
638    }
639    status_t res = consumer->lockNextBuffer(buffer);
640    if (res != NO_ERROR) {
641        ALOGE("%s Fail to lockNextBuffer with error: %d ", __FUNCTION__, res);
642        return false;
643    }
644
645
646    // Check if the left-top corner of the crop rect is origin, we currently assume this point is
647    // zero, will revist this once this assumption turns out problematic.
648    Point lt = buffer->crop.leftTop();
649    if (lt.x != 0 || lt.y != 0) {
650        ALOGE("crop left: %d, top = %d", lt.x, lt.y);
651        jniThrowException(env, "java/lang/UnsupportedOperationException",
652                          "crop left top corner need to at origin");
653    }
654
655    // Check if the producer buffer configurations match what ImageReader configured.
656    // We want to fail for the very first image because this case is too bad.
657    int outputWidth = buffer->width;
658    int outputHeight = buffer->height;
659
660    // Correct with/height when crop is set.
661    if (buffer->crop.getWidth() > 0) {
662        outputWidth = buffer->crop.getWidth() + 1;
663    }
664    if (buffer->crop.getHeight() > 0) {
665        outputHeight = buffer->crop.getHeight() + 1;
666    }
667
668    int imageReaderWidth = ctx->getBufferWidth();
669    int imageReaderHeight = ctx->getBufferHeight();
670    if (imageReaderWidth != outputWidth
671            || imageReaderHeight != outputHeight) {
672        // Spew warning for now, since MediaCodec decoder has a bug to setup the right crop
673        // TODO: make it throw exception once the decoder bug is fixed.
674        ALOGW("Producer buffer size: %dx%d, doesn't match ImageReader configured size: %dx%d",
675              outputWidth, outputHeight, imageReaderWidth, imageReaderHeight);
676    }
677
678    if (ctx->getBufferFormat() != buffer->format) {
679        // Return the buffer to the queue.
680        consumer->unlockBuffer(*buffer);
681        ctx->returnLockedBuffer(buffer);
682
683        // Throw exception
684        ALOGE("Producer output buffer format: 0x%x, ImageReader configured format: 0x%x",
685              buffer->format, ctx->getBufferFormat());
686        String8 msg;
687        msg.appendFormat("The producer output buffer format 0x%x doesn't "
688                "match the ImageReader's configured buffer format 0x%x.",
689                buffer->format, ctx->getBufferFormat());
690        jniThrowException(env, "java/lang/UnsupportedOperationException",
691                msg.string());
692        return false;
693    }
694    // Set SurfaceImage instance member variables
695    Image_setBuffer(env, image, buffer);
696    env->SetLongField(image, gSurfaceImageClassInfo.mTimestamp,
697            static_cast<jlong>(buffer->timestamp));
698
699    return true;
700}
701
702static jobject ImageReader_getSurface(JNIEnv* env, jobject thiz)
703{
704    ALOGV("%s: ", __FUNCTION__);
705
706    CpuConsumer* consumer = ImageReader_getCpuConsumer(env, thiz);
707    if (consumer == NULL) {
708        jniThrowRuntimeException(env, "CpuConsumer is uninitialized");
709        return NULL;
710    }
711
712    // Wrap the IGBP in a Java-language Surface.
713    return android_view_Surface_createFromIGraphicBufferProducer(
714            env, consumer->getProducerInterface());
715}
716
717static jobject Image_createSurfacePlane(JNIEnv* env, jobject thiz, int idx)
718{
719    int rowStride, pixelStride;
720    ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
721
722    CpuConsumer::LockedBuffer* buffer = Image_getLockedBuffer(env, thiz);
723
724    ALOG_ASSERT(buffer != NULL);
725    if (buffer == NULL) {
726        jniThrowException(env, "java/lang/IllegalStateException", "Image was released");
727    }
728    rowStride = Image_imageGetRowStride(env, buffer, idx);
729    pixelStride = Image_imageGetPixelStride(env, buffer, idx);
730
731    jobject surfPlaneObj = env->NewObject(gSurfacePlaneClassInfo.clazz,
732            gSurfacePlaneClassInfo.ctor, thiz, idx, rowStride, pixelStride);
733
734    return surfPlaneObj;
735}
736
737static jobject Image_getByteBuffer(JNIEnv* env, jobject thiz, int idx)
738{
739    uint8_t *base = NULL;
740    uint32_t size = 0;
741    jobject byteBuffer;
742
743    ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
744
745    CpuConsumer::LockedBuffer* buffer = Image_getLockedBuffer(env, thiz);
746
747    if (buffer == NULL) {
748        jniThrowException(env, "java/lang/IllegalStateException", "Image was released");
749    }
750
751    // Create byteBuffer from native buffer
752    Image_getLockedBufferInfo(env, buffer, idx, &base, &size);
753    byteBuffer = env->NewDirectByteBuffer(base, size);
754    // TODO: throw dvm exOutOfMemoryError?
755    if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
756        jniThrowException(env, "java/lang/IllegalStateException", "Failed to allocate ByteBuffer");
757    }
758
759    return byteBuffer;
760}
761
762} // extern "C"
763
764// ----------------------------------------------------------------------------
765
766static JNINativeMethod gImageReaderMethods[] = {
767    {"nativeClassInit",        "()V",                        (void*)ImageReader_classInit },
768    {"nativeInit",             "(Ljava/lang/Object;IIII)V",  (void*)ImageReader_init },
769    {"nativeClose",            "()V",                        (void*)ImageReader_close },
770    {"nativeReleaseImage",     "(Landroid/media/Image;)V",   (void*)ImageReader_imageRelease },
771    {"nativeImageSetup",       "(Landroid/media/Image;)Z",    (void*)ImageReader_imageSetup },
772    {"nativeGetSurface",       "()Landroid/view/Surface;",   (void*)ImageReader_getSurface },
773};
774
775static JNINativeMethod gImageMethods[] = {
776    {"nativeImageGetBuffer",   "(I)Ljava/nio/ByteBuffer;",   (void*)Image_getByteBuffer },
777    {"nativeCreatePlane",      "(I)Landroid/media/ImageReader$SurfaceImage$SurfacePlane;",
778                                                             (void*)Image_createSurfacePlane },
779};
780
781int register_android_media_ImageReader(JNIEnv *env) {
782
783    int ret1 = AndroidRuntime::registerNativeMethods(env,
784                   "android/media/ImageReader", gImageReaderMethods, NELEM(gImageReaderMethods));
785
786    int ret2 = AndroidRuntime::registerNativeMethods(env,
787                   "android/media/ImageReader$SurfaceImage", gImageMethods, NELEM(gImageMethods));
788
789    return (ret1 || ret2);
790}
791