blob: 35317e1c51e0d98d082033b6597a756a65abcdbd [file] [log] [blame]
Zhijun He212e78d2013-06-07 11:36:23 -07001/*
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>
Jeff Brownef961212013-08-05 20:39:29 -070022#include <utils/String8.h>
Zhijun He212e78d2013-06-07 11:36:23 -070023
24#include <cstdio>
25
26#include <gui/CpuConsumer.h>
27#include <gui/Surface.h>
Zhijun He534046d2013-07-01 11:03:41 -070028#include <camera3.h>
Zhijun He212e78d2013-06-07 11:36:23 -070029
30#include <android_runtime/AndroidRuntime.h>
31#include <android_runtime/android_view_Surface.h>
32
33#include <jni.h>
34#include <JNIHelp.h>
35
Igor Murashkin5096def2014-06-24 10:49:11 -070036#include <stdint.h>
37#include <inttypes.h>
38
Zhijun He212e78d2013-06-07 11:36:23 -070039#define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
40
Zhijun He212e78d2013-06-07 11:36:23 -070041#define ANDROID_MEDIA_IMAGEREADER_CTX_JNI_ID "mNativeContext"
42#define ANDROID_MEDIA_SURFACEIMAGE_BUFFER_JNI_ID "mLockedBuffer"
43#define ANDROID_MEDIA_SURFACEIMAGE_TS_JNI_ID "mTimestamp"
44
45// ----------------------------------------------------------------------------
46
47using namespace android;
48
49enum {
50 IMAGE_READER_MAX_NUM_PLANES = 3,
51};
52
Igor Murashkine3351f12013-09-13 13:08:04 -070053enum {
54 ACQUIRE_SUCCESS = 0,
55 ACQUIRE_NO_BUFFERS = 1,
56 ACQUIRE_MAX_IMAGES = 2,
57};
58
Jeff Brownef961212013-08-05 20:39:29 -070059static struct {
60 jfieldID mNativeContext;
61 jmethodID postEventFromNative;
62} gImageReaderClassInfo;
Zhijun He212e78d2013-06-07 11:36:23 -070063
Jeff Brownef961212013-08-05 20:39:29 -070064static struct {
65 jfieldID mLockedBuffer;
66 jfieldID mTimestamp;
67} gSurfaceImageClassInfo;
68
69static struct {
Zhijun He212e78d2013-06-07 11:36:23 -070070 jclass clazz;
71 jmethodID ctor;
Jeff Brownef961212013-08-05 20:39:29 -070072} gSurfacePlaneClassInfo;
Zhijun He212e78d2013-06-07 11:36:23 -070073
74// ----------------------------------------------------------------------------
75
76class JNIImageReaderContext : public CpuConsumer::FrameAvailableListener
77{
78public:
79 JNIImageReaderContext(JNIEnv* env, jobject weakThiz, jclass clazz, int maxImages);
80
81 virtual ~JNIImageReaderContext();
82
83 virtual void onFrameAvailable();
84
85 CpuConsumer::LockedBuffer* getLockedBuffer();
86
87 void returnLockedBuffer(CpuConsumer::LockedBuffer* buffer);
88
Mathias Agopian52a9a102013-08-02 01:38:38 -070089 void setCpuConsumer(const sp<CpuConsumer>& consumer) { mConsumer = consumer; }
Zhijun He212e78d2013-06-07 11:36:23 -070090 CpuConsumer* getCpuConsumer() { return mConsumer.get(); }
91
Dan Stoza5b3c7c12014-03-12 16:44:45 -070092 void setProducer(const sp<IGraphicBufferProducer>& producer) { mProducer = producer; }
93 IGraphicBufferProducer* getProducer() { return mProducer.get(); }
Zhijun He212e78d2013-06-07 11:36:23 -070094
95 void setBufferFormat(int format) { mFormat = format; }
96 int getBufferFormat() { return mFormat; }
97
98 void setBufferWidth(int width) { mWidth = width; }
99 int getBufferWidth() { return mWidth; }
100
101 void setBufferHeight(int height) { mHeight = height; }
102 int getBufferHeight() { return mHeight; }
103
104private:
105 static JNIEnv* getJNIEnv(bool* needsDetach);
106 static void detachJNI();
107
108 List<CpuConsumer::LockedBuffer*> mBuffers;
109 sp<CpuConsumer> mConsumer;
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700110 sp<IGraphicBufferProducer> mProducer;
Zhijun He212e78d2013-06-07 11:36:23 -0700111 jobject mWeakThiz;
112 jclass mClazz;
113 int mFormat;
114 int mWidth;
115 int mHeight;
116};
117
118JNIImageReaderContext::JNIImageReaderContext(JNIEnv* env,
119 jobject weakThiz, jclass clazz, int maxImages) :
120 mWeakThiz(env->NewGlobalRef(weakThiz)),
121 mClazz((jclass)env->NewGlobalRef(clazz)) {
122 for (int i = 0; i < maxImages; i++) {
123 CpuConsumer::LockedBuffer *buffer = new CpuConsumer::LockedBuffer;
124 mBuffers.push_back(buffer);
125 }
126}
127
128JNIEnv* JNIImageReaderContext::getJNIEnv(bool* needsDetach) {
129 LOG_ALWAYS_FATAL_IF(needsDetach == NULL, "needsDetach is null!!!");
130 *needsDetach = false;
131 JNIEnv* env = AndroidRuntime::getJNIEnv();
132 if (env == NULL) {
133 JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL};
134 JavaVM* vm = AndroidRuntime::getJavaVM();
135 int result = vm->AttachCurrentThread(&env, (void*) &args);
136 if (result != JNI_OK) {
137 ALOGE("thread attach failed: %#x", result);
138 return NULL;
139 }
140 *needsDetach = true;
141 }
142 return env;
143}
144
145void JNIImageReaderContext::detachJNI() {
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
153CpuConsumer::LockedBuffer* JNIImageReaderContext::getLockedBuffer() {
154 if (mBuffers.empty()) {
155 return NULL;
156 }
157 // Return a LockedBuffer pointer and remove it from the list
158 List<CpuConsumer::LockedBuffer*>::iterator it = mBuffers.begin();
159 CpuConsumer::LockedBuffer* buffer = *it;
160 mBuffers.erase(it);
161 return buffer;
162}
163
Igor Murashkind901c032013-08-27 15:19:55 -0700164void JNIImageReaderContext::returnLockedBuffer(CpuConsumer::LockedBuffer* buffer) {
Zhijun He212e78d2013-06-07 11:36:23 -0700165 mBuffers.push_back(buffer);
166}
167
168JNIImageReaderContext::~JNIImageReaderContext() {
169 bool needsDetach = false;
170 JNIEnv* env = getJNIEnv(&needsDetach);
171 if (env != NULL) {
172 env->DeleteGlobalRef(mWeakThiz);
173 env->DeleteGlobalRef(mClazz);
174 } else {
175 ALOGW("leaking JNI object references");
176 }
177 if (needsDetach) {
178 detachJNI();
179 }
180
181 // Delete LockedBuffers
182 for (List<CpuConsumer::LockedBuffer *>::iterator it = mBuffers.begin();
183 it != mBuffers.end(); it++) {
184 delete *it;
185 }
186 mBuffers.clear();
187 mConsumer.clear();
188}
189
190void JNIImageReaderContext::onFrameAvailable()
191{
192 ALOGV("%s: frame available", __FUNCTION__);
193 bool needsDetach = false;
194 JNIEnv* env = getJNIEnv(&needsDetach);
195 if (env != NULL) {
Jeff Brownef961212013-08-05 20:39:29 -0700196 env->CallStaticVoidMethod(mClazz, gImageReaderClassInfo.postEventFromNative, mWeakThiz);
Zhijun He212e78d2013-06-07 11:36:23 -0700197 } else {
198 ALOGW("onFrameAvailable event will not posted");
199 }
200 if (needsDetach) {
201 detachJNI();
202 }
203}
204
205// ----------------------------------------------------------------------------
206
207extern "C" {
208
209static JNIImageReaderContext* ImageReader_getContext(JNIEnv* env, jobject thiz)
210{
211 JNIImageReaderContext *ctx;
212 ctx = reinterpret_cast<JNIImageReaderContext *>
Jeff Brownef961212013-08-05 20:39:29 -0700213 (env->GetLongField(thiz, gImageReaderClassInfo.mNativeContext));
Zhijun He212e78d2013-06-07 11:36:23 -0700214 return ctx;
215}
216
217static CpuConsumer* ImageReader_getCpuConsumer(JNIEnv* env, jobject thiz)
218{
219 ALOGV("%s:", __FUNCTION__);
220 JNIImageReaderContext* const ctx = ImageReader_getContext(env, thiz);
221 if (ctx == NULL) {
222 jniThrowRuntimeException(env, "ImageReaderContext is not initialized");
223 return NULL;
224 }
225 return ctx->getCpuConsumer();
226}
227
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700228static IGraphicBufferProducer* ImageReader_getProducer(JNIEnv* env, jobject thiz)
Mathias Agopian52a9a102013-08-02 01:38:38 -0700229{
230 ALOGV("%s:", __FUNCTION__);
231 JNIImageReaderContext* const ctx = ImageReader_getContext(env, thiz);
232 if (ctx == NULL) {
233 jniThrowRuntimeException(env, "ImageReaderContext is not initialized");
234 return NULL;
235 }
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700236 return ctx->getProducer();
Mathias Agopian52a9a102013-08-02 01:38:38 -0700237}
238
Zhijun He212e78d2013-06-07 11:36:23 -0700239static void ImageReader_setNativeContext(JNIEnv* env,
240 jobject thiz, sp<JNIImageReaderContext> ctx)
241{
242 ALOGV("%s:", __FUNCTION__);
243 JNIImageReaderContext* const p = ImageReader_getContext(env, thiz);
244 if (ctx != 0) {
245 ctx->incStrong((void*)ImageReader_setNativeContext);
246 }
247 if (p) {
248 p->decStrong((void*)ImageReader_setNativeContext);
249 }
Jeff Brownef961212013-08-05 20:39:29 -0700250 env->SetLongField(thiz, gImageReaderClassInfo.mNativeContext,
251 reinterpret_cast<jlong>(ctx.get()));
Zhijun He212e78d2013-06-07 11:36:23 -0700252}
253
254static CpuConsumer::LockedBuffer* Image_getLockedBuffer(JNIEnv* env, jobject image)
255{
Jeff Brownef961212013-08-05 20:39:29 -0700256 return reinterpret_cast<CpuConsumer::LockedBuffer*>(
257 env->GetLongField(image, gSurfaceImageClassInfo.mLockedBuffer));
Zhijun He212e78d2013-06-07 11:36:23 -0700258}
259
260static void Image_setBuffer(JNIEnv* env, jobject thiz,
261 const CpuConsumer::LockedBuffer* buffer)
262{
Jeff Brownef961212013-08-05 20:39:29 -0700263 env->SetLongField(thiz, gSurfaceImageClassInfo.mLockedBuffer, reinterpret_cast<jlong>(buffer));
Zhijun He212e78d2013-06-07 11:36:23 -0700264}
265
266// Some formats like JPEG defined with different values between android.graphics.ImageFormat and
267// graphics.h, need convert to the one defined in graphics.h here.
268static int Image_getPixelFormat(JNIEnv* env, int format)
269{
Zhijun Hed1988a92014-07-01 04:15:09 -0700270 int jpegFormat;
Zhijun He212e78d2013-06-07 11:36:23 -0700271 jfieldID fid;
272
273 ALOGV("%s: format = 0x%x", __FUNCTION__, format);
274
275 jclass imageFormatClazz = env->FindClass("android/graphics/ImageFormat");
276 ALOG_ASSERT(imageFormatClazz != NULL);
277
278 fid = env->GetStaticFieldID(imageFormatClazz, "JPEG", "I");
279 jpegFormat = env->GetStaticIntField(imageFormatClazz, fid);
Zhijun He212e78d2013-06-07 11:36:23 -0700280
Zhijun Hea5e15282014-04-24 14:08:51 -0700281 // Translate the JPEG to BLOB for camera purpose.
Zhijun He212e78d2013-06-07 11:36:23 -0700282 if (format == jpegFormat) {
283 format = HAL_PIXEL_FORMAT_BLOB;
284 }
Zhijun He212e78d2013-06-07 11:36:23 -0700285
286 return format;
287}
288
Zhijun He534046d2013-07-01 11:03:41 -0700289static uint32_t Image_getJpegSize(CpuConsumer::LockedBuffer* buffer)
290{
291 ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
292 uint32_t size = 0;
293 uint32_t width = buffer->width;
294 uint8_t* jpegBuffer = buffer->data;
295
296 // First check for JPEG transport header at the end of the buffer
297 uint8_t* header = jpegBuffer + (width - sizeof(struct camera3_jpeg_blob));
298 struct camera3_jpeg_blob *blob = (struct camera3_jpeg_blob*)(header);
299 if (blob->jpeg_blob_id == CAMERA3_JPEG_BLOB_ID) {
300 size = blob->jpeg_size;
301 ALOGV("%s: Jpeg size = %d", __FUNCTION__, size);
302 }
303
304 // failed to find size, default to whole buffer
305 if (size == 0) {
Igor Murashkin5096def2014-06-24 10:49:11 -0700306 /*
307 * This is a problem because not including the JPEG header
308 * means that in certain rare situations a regular JPEG blob
309 * will be misidentified as having a header, in which case
310 * we will get a garbage size value.
311 */
312 ALOGW("%s: No JPEG header detected, defaulting to size=width=%d",
313 __FUNCTION__, width);
Zhijun He534046d2013-07-01 11:03:41 -0700314 size = width;
315 }
316
317 return size;
318}
319
Zhijun He212e78d2013-06-07 11:36:23 -0700320static void Image_getLockedBufferInfo(JNIEnv* env, CpuConsumer::LockedBuffer* buffer, int idx,
321 uint8_t **base, uint32_t *size)
322{
323 ALOG_ASSERT(buffer != NULL, "Input buffer is NULL!!!");
324 ALOG_ASSERT(base != NULL, "base is NULL!!!");
325 ALOG_ASSERT(size != NULL, "size is NULL!!!");
326 ALOG_ASSERT((idx < IMAGE_READER_MAX_NUM_PLANES) && (idx >= 0));
327
Zhijun He7f4d3142013-07-23 07:54:38 -0700328 ALOGV("%s: buffer: %p", __FUNCTION__, buffer);
Zhijun He212e78d2013-06-07 11:36:23 -0700329
330 uint32_t dataSize, ySize, cSize, cStride;
331 uint8_t *cb, *cr;
332 uint8_t *pData = NULL;
Zhijun He708e3592013-08-05 14:56:11 -0700333 int bytesPerPixel = 0;
Zhijun He212e78d2013-06-07 11:36:23 -0700334
335 dataSize = ySize = cSize = cStride = 0;
336 int32_t fmt = buffer->format;
337 switch (fmt) {
338 case HAL_PIXEL_FORMAT_YCbCr_420_888:
339 pData =
340 (idx == 0) ?
341 buffer->data :
342 (idx == 1) ?
343 buffer->dataCb :
344 buffer->dataCr;
345 if (idx == 0) {
346 dataSize = buffer->stride * buffer->height;
347 } else {
348 dataSize = buffer->chromaStride * buffer->height / 2;
349 }
350 break;
351 // NV21
352 case HAL_PIXEL_FORMAT_YCrCb_420_SP:
353 cr = buffer->data + (buffer->stride * buffer->height);
354 cb = cr + 1;
355 ySize = buffer->width * buffer->height;
356 cSize = buffer->width * buffer->height / 2;
357
358 pData =
359 (idx == 0) ?
360 buffer->data :
361 (idx == 1) ?
362 cb:
363 cr;
364
365 dataSize = (idx == 0) ? ySize : cSize;
366 break;
367 case HAL_PIXEL_FORMAT_YV12:
368 // Y and C stride need to be 16 pixel aligned.
369 LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
370 "Stride is not 16 pixel aligned %d", buffer->stride);
371
372 ySize = buffer->stride * buffer->height;
373 cStride = ALIGN(buffer->stride / 2, 16);
374 cr = buffer->data + ySize;
375 cSize = cStride * buffer->height / 2;
376 cb = cr + cSize;
377
378 pData =
379 (idx == 0) ?
380 buffer->data :
381 (idx == 1) ?
382 cb :
383 cr;
384 dataSize = (idx == 0) ? ySize : cSize;
385 break;
386 case HAL_PIXEL_FORMAT_Y8:
387 // Single plane, 8bpp.
388 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
389
390 pData = buffer->data;
391 dataSize = buffer->stride * buffer->height;
392 break;
393 case HAL_PIXEL_FORMAT_Y16:
Zhijun He977ad8d2014-04-08 16:59:29 -0700394 bytesPerPixel = 2;
Zhijun He212e78d2013-06-07 11:36:23 -0700395 // Single plane, 16bpp, strides are specified in pixels, not in bytes
396 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
397
398 pData = buffer->data;
Zhijun He977ad8d2014-04-08 16:59:29 -0700399 dataSize = buffer->stride * buffer->height * bytesPerPixel;
Zhijun He212e78d2013-06-07 11:36:23 -0700400 break;
401 case HAL_PIXEL_FORMAT_BLOB:
402 // Used for JPEG data, height must be 1, width == size, single plane.
403 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
404 ALOG_ASSERT(buffer->height == 1, "JPEG should has height value %d", buffer->height);
405
406 pData = buffer->data;
Zhijun He534046d2013-07-01 11:03:41 -0700407 dataSize = Image_getJpegSize(buffer);
Zhijun He212e78d2013-06-07 11:36:23 -0700408 break;
409 case HAL_PIXEL_FORMAT_RAW_SENSOR:
410 // Single plane 16bpp bayer data.
Zhijun He977ad8d2014-04-08 16:59:29 -0700411 bytesPerPixel = 2;
Zhijun He212e78d2013-06-07 11:36:23 -0700412 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
413 pData = buffer->data;
Zhijun He977ad8d2014-04-08 16:59:29 -0700414 dataSize = buffer->stride * buffer->height * bytesPerPixel;
Zhijun He212e78d2013-06-07 11:36:23 -0700415 break;
Zhijun Hed1988a92014-07-01 04:15:09 -0700416 case HAL_PIXEL_FORMAT_RAW10:
417 // Single plane 10bpp bayer data.
418 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
419 LOG_ALWAYS_FATAL_IF(buffer->width % 4,
420 "Width is not multiple of 4 %d", buffer->width);
421 LOG_ALWAYS_FATAL_IF(buffer->height % 2,
422 "Height is not even %d", buffer->height);
423 pData = buffer->data;
424 dataSize = buffer->width * buffer->height * 10 / 8;
425 break;
Zhijun He708e3592013-08-05 14:56:11 -0700426 case HAL_PIXEL_FORMAT_RGBA_8888:
427 case HAL_PIXEL_FORMAT_RGBX_8888:
428 // Single plane, 32bpp.
429 bytesPerPixel = 4;
430 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
431 pData = buffer->data;
432 dataSize = buffer->stride * buffer->height * bytesPerPixel;
433 break;
434 case HAL_PIXEL_FORMAT_RGB_565:
435 // Single plane, 16bpp.
436 bytesPerPixel = 2;
437 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
438 pData = buffer->data;
439 dataSize = buffer->stride * buffer->height * bytesPerPixel;
440 break;
441 case HAL_PIXEL_FORMAT_RGB_888:
442 // Single plane, 24bpp.
443 bytesPerPixel = 3;
444 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
445 pData = buffer->data;
446 dataSize = buffer->stride * buffer->height * bytesPerPixel;
447 break;
Zhijun He212e78d2013-06-07 11:36:23 -0700448 default:
449 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
450 "Pixel format: 0x%x is unsupported", fmt);
451 break;
452 }
453
454 *base = pData;
455 *size = dataSize;
456}
457
458static jint Image_imageGetPixelStride(JNIEnv* env, CpuConsumer::LockedBuffer* buffer, int idx)
459{
460 ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
461 ALOG_ASSERT((idx < IMAGE_READER_MAX_NUM_PLANES) && (idx >= 0), "Index is out of range:%d", idx);
462
463 int pixelStride = 0;
464 ALOG_ASSERT(buffer != NULL, "buffer is NULL");
465
466 int32_t fmt = buffer->format;
467 switch (fmt) {
468 case HAL_PIXEL_FORMAT_YCbCr_420_888:
469 pixelStride = (idx == 0) ? 1 : buffer->chromaStep;
470 break;
471 case HAL_PIXEL_FORMAT_YCrCb_420_SP:
472 pixelStride = (idx == 0) ? 1 : 2;
473 break;
474 case HAL_PIXEL_FORMAT_Y8:
475 // Single plane 8bpp data.
476 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
477 pixelStride;
478 break;
479 case HAL_PIXEL_FORMAT_YV12:
480 pixelStride = 1;
481 break;
482 case HAL_PIXEL_FORMAT_BLOB:
Zhijun Hed1988a92014-07-01 04:15:09 -0700483 case HAL_PIXEL_FORMAT_RAW10:
484 // Blob is used for JPEG data, RAW10 is used for 10-bit raw data, they are
485 // single plane, row and pixel strides are 0.
Zhijun He212e78d2013-06-07 11:36:23 -0700486 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
487 pixelStride = 0;
488 break;
489 case HAL_PIXEL_FORMAT_Y16:
490 case HAL_PIXEL_FORMAT_RAW_SENSOR:
Zhijun He708e3592013-08-05 14:56:11 -0700491 case HAL_PIXEL_FORMAT_RGB_565:
Zhijun He212e78d2013-06-07 11:36:23 -0700492 // Single plane 16bpp data.
493 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
494 pixelStride = 2;
495 break;
Zhijun He708e3592013-08-05 14:56:11 -0700496 case HAL_PIXEL_FORMAT_RGBA_8888:
497 case HAL_PIXEL_FORMAT_RGBX_8888:
498 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
499 pixelStride = 4;
500 break;
501 case HAL_PIXEL_FORMAT_RGB_888:
502 // Single plane, 24bpp.
503 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
504 pixelStride = 3;
505 break;
Zhijun He212e78d2013-06-07 11:36:23 -0700506 default:
507 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
508 "Pixel format: 0x%x is unsupported", fmt);
509 break;
510 }
511
512 return pixelStride;
513}
514
515static jint Image_imageGetRowStride(JNIEnv* env, CpuConsumer::LockedBuffer* buffer, int idx)
516{
517 ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
518 ALOG_ASSERT((idx < IMAGE_READER_MAX_NUM_PLANES) && (idx >= 0));
519
520 int rowStride = 0;
521 ALOG_ASSERT(buffer != NULL, "buffer is NULL");
522
523 int32_t fmt = buffer->format;
524
525 switch (fmt) {
526 case HAL_PIXEL_FORMAT_YCbCr_420_888:
527 rowStride = (idx == 0) ? buffer->stride : buffer->chromaStride;
528 break;
529 case HAL_PIXEL_FORMAT_YCrCb_420_SP:
530 rowStride = buffer->width;
531 break;
532 case HAL_PIXEL_FORMAT_YV12:
533 LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
534 "Stride is not 16 pixel aligned %d", buffer->stride);
535 rowStride = (idx == 0) ? buffer->stride : ALIGN(buffer->stride / 2, 16);
536 break;
537 case HAL_PIXEL_FORMAT_BLOB:
Zhijun Hed1988a92014-07-01 04:15:09 -0700538 case HAL_PIXEL_FORMAT_RAW10:
539 // Blob is used for JPEG data, RAW10 is used for 10-bit raw data, they are
540 // single plane, row and pixel strides are 0.
Zhijun He212e78d2013-06-07 11:36:23 -0700541 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
542 rowStride = 0;
543 break;
544 case HAL_PIXEL_FORMAT_Y8:
545 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
546 LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
547 "Stride is not 16 pixel aligned %d", buffer->stride);
548 rowStride = buffer->stride;
549 break;
550 case HAL_PIXEL_FORMAT_Y16:
551 case HAL_PIXEL_FORMAT_RAW_SENSOR:
552 // In native side, strides are specified in pixels, not in bytes.
553 // Single plane 16bpp bayer data. even width/height,
554 // row stride multiple of 16 pixels (32 bytes)
555 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
556 LOG_ALWAYS_FATAL_IF(buffer->stride % 16,
557 "Stride is not 16 pixel aligned %d", buffer->stride);
558 rowStride = buffer->stride * 2;
559 break;
Zhijun He708e3592013-08-05 14:56:11 -0700560 case HAL_PIXEL_FORMAT_RGB_565:
561 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
562 rowStride = buffer->stride * 2;
563 break;
564 case HAL_PIXEL_FORMAT_RGBA_8888:
565 case HAL_PIXEL_FORMAT_RGBX_8888:
566 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
567 rowStride = buffer->stride * 4;
568 break;
569 case HAL_PIXEL_FORMAT_RGB_888:
570 // Single plane, 24bpp.
571 ALOG_ASSERT(idx == 0, "Wrong index: %d", idx);
572 rowStride = buffer->stride * 3;
573 break;
Zhijun He212e78d2013-06-07 11:36:23 -0700574 default:
575 ALOGE("%s Pixel format: 0x%x is unsupported", __FUNCTION__, fmt);
576 jniThrowException(env, "java/lang/UnsupportedOperationException",
577 "unsupported buffer format");
578 break;
579 }
580
581 return rowStride;
582}
583
584// ----------------------------------------------------------------------------
585
586static void ImageReader_classInit(JNIEnv* env, jclass clazz)
587{
588 ALOGV("%s:", __FUNCTION__);
589
590 jclass imageClazz = env->FindClass("android/media/ImageReader$SurfaceImage");
591 LOG_ALWAYS_FATAL_IF(imageClazz == NULL,
592 "can't find android/graphics/ImageReader$SurfaceImage");
Jeff Brownef961212013-08-05 20:39:29 -0700593 gSurfaceImageClassInfo.mLockedBuffer = env->GetFieldID(
594 imageClazz, ANDROID_MEDIA_SURFACEIMAGE_BUFFER_JNI_ID, "J");
595 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mLockedBuffer == NULL,
Zhijun He212e78d2013-06-07 11:36:23 -0700596 "can't find android/graphics/ImageReader.%s",
597 ANDROID_MEDIA_SURFACEIMAGE_BUFFER_JNI_ID);
598
Jeff Brownef961212013-08-05 20:39:29 -0700599 gSurfaceImageClassInfo.mTimestamp = env->GetFieldID(
600 imageClazz, ANDROID_MEDIA_SURFACEIMAGE_TS_JNI_ID, "J");
601 LOG_ALWAYS_FATAL_IF(gSurfaceImageClassInfo.mTimestamp == NULL,
Zhijun He212e78d2013-06-07 11:36:23 -0700602 "can't find android/graphics/ImageReader.%s",
603 ANDROID_MEDIA_SURFACEIMAGE_TS_JNI_ID);
604
Jeff Brownef961212013-08-05 20:39:29 -0700605 gImageReaderClassInfo.mNativeContext = env->GetFieldID(
606 clazz, ANDROID_MEDIA_IMAGEREADER_CTX_JNI_ID, "J");
607 LOG_ALWAYS_FATAL_IF(gImageReaderClassInfo.mNativeContext == NULL,
Zhijun He212e78d2013-06-07 11:36:23 -0700608 "can't find android/graphics/ImageReader.%s",
609 ANDROID_MEDIA_IMAGEREADER_CTX_JNI_ID);
610
Jeff Brownef961212013-08-05 20:39:29 -0700611 gImageReaderClassInfo.postEventFromNative = env->GetStaticMethodID(
612 clazz, "postEventFromNative", "(Ljava/lang/Object;)V");
613 LOG_ALWAYS_FATAL_IF(gImageReaderClassInfo.postEventFromNative == NULL,
Zhijun He212e78d2013-06-07 11:36:23 -0700614 "can't find android/graphics/ImageReader.postEventFromNative");
615
616 jclass planeClazz = env->FindClass("android/media/ImageReader$SurfaceImage$SurfacePlane");
617 LOG_ALWAYS_FATAL_IF(planeClazz == NULL, "Can not find SurfacePlane class");
618 // FindClass only gives a local reference of jclass object.
Jeff Brownef961212013-08-05 20:39:29 -0700619 gSurfacePlaneClassInfo.clazz = (jclass) env->NewGlobalRef(planeClazz);
620 gSurfacePlaneClassInfo.ctor = env->GetMethodID(gSurfacePlaneClassInfo.clazz, "<init>",
621 "(Landroid/media/ImageReader$SurfaceImage;III)V");
622 LOG_ALWAYS_FATAL_IF(gSurfacePlaneClassInfo.ctor == NULL,
623 "Can not find SurfacePlane constructor");
Zhijun He212e78d2013-06-07 11:36:23 -0700624}
625
626static void ImageReader_init(JNIEnv* env, jobject thiz, jobject weakThiz,
627 jint width, jint height, jint format, jint maxImages)
628{
629 status_t res;
630 int nativeFormat;
631
632 ALOGV("%s: width:%d, height: %d, format: 0x%x, maxImages:%d",
633 __FUNCTION__, width, height, format, maxImages);
634
635 nativeFormat = Image_getPixelFormat(env, format);
636
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700637 sp<IGraphicBufferProducer> gbProducer;
638 sp<IGraphicBufferConsumer> gbConsumer;
639 BufferQueue::createBufferQueue(&gbProducer, &gbConsumer);
640 sp<CpuConsumer> consumer = new CpuConsumer(gbConsumer, maxImages,
Igor Murashkindd064322013-08-14 19:05:17 -0700641 /*controlledByApp*/true);
Zhijun He212e78d2013-06-07 11:36:23 -0700642 // TODO: throw dvm exOutOfMemoryError?
643 if (consumer == NULL) {
644 jniThrowRuntimeException(env, "Failed to allocate native CpuConsumer");
645 return;
646 }
647
648 jclass clazz = env->GetObjectClass(thiz);
649 if (clazz == NULL) {
650 jniThrowRuntimeException(env, "Can't find android/graphics/ImageReader");
651 return;
652 }
653 sp<JNIImageReaderContext> ctx(new JNIImageReaderContext(env, weakThiz, clazz, maxImages));
654 ctx->setCpuConsumer(consumer);
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700655 ctx->setProducer(gbProducer);
Zhijun He212e78d2013-06-07 11:36:23 -0700656 consumer->setFrameAvailableListener(ctx);
657 ImageReader_setNativeContext(env, thiz, ctx);
658 ctx->setBufferFormat(nativeFormat);
659 ctx->setBufferWidth(width);
660 ctx->setBufferHeight(height);
661
662 // Set the width/height/format to the CpuConsumer
663 res = consumer->setDefaultBufferSize(width, height);
664 if (res != OK) {
665 jniThrowException(env, "java/lang/IllegalStateException",
666 "Failed to set CpuConsumer buffer size");
667 return;
668 }
669 res = consumer->setDefaultBufferFormat(nativeFormat);
670 if (res != OK) {
671 jniThrowException(env, "java/lang/IllegalStateException",
672 "Failed to set CpuConsumer buffer format");
673 }
674}
675
676static void ImageReader_close(JNIEnv* env, jobject thiz)
677{
678 ALOGV("%s:", __FUNCTION__);
679
680 JNIImageReaderContext* const ctx = ImageReader_getContext(env, thiz);
681 if (ctx == NULL) {
682 // ImageReader is already closed.
683 return;
684 }
685
686 CpuConsumer* consumer = ImageReader_getCpuConsumer(env, thiz);
687 if (consumer != NULL) {
688 consumer->abandon();
689 consumer->setFrameAvailableListener(NULL);
690 }
691 ImageReader_setNativeContext(env, thiz, NULL);
692}
693
694static void ImageReader_imageRelease(JNIEnv* env, jobject thiz, jobject image)
695{
696 ALOGV("%s:", __FUNCTION__);
697 JNIImageReaderContext* ctx = ImageReader_getContext(env, thiz);
698 if (ctx == NULL) {
699 ALOGW("ImageReader#close called before Image#close, consider calling Image#close first");
700 return;
701 }
702
703 CpuConsumer* consumer = ctx->getCpuConsumer();
704 CpuConsumer::LockedBuffer* buffer = Image_getLockedBuffer(env, image);
705 if (!buffer) {
706 ALOGW("Image already released!!!");
707 return;
708 }
709 consumer->unlockBuffer(*buffer);
710 Image_setBuffer(env, image, NULL);
711 ctx->returnLockedBuffer(buffer);
712}
713
Igor Murashkine3351f12013-09-13 13:08:04 -0700714static jint ImageReader_imageSetup(JNIEnv* env, jobject thiz,
Zhijun He212e78d2013-06-07 11:36:23 -0700715 jobject image)
716{
717 ALOGV("%s:", __FUNCTION__);
718 JNIImageReaderContext* ctx = ImageReader_getContext(env, thiz);
719 if (ctx == NULL) {
720 jniThrowRuntimeException(env, "ImageReaderContext is not initialized");
Igor Murashkine3351f12013-09-13 13:08:04 -0700721 return -1;
Zhijun He212e78d2013-06-07 11:36:23 -0700722 }
723
724 CpuConsumer* consumer = ctx->getCpuConsumer();
725 CpuConsumer::LockedBuffer* buffer = ctx->getLockedBuffer();
726 if (buffer == NULL) {
Igor Murashkind901c032013-08-27 15:19:55 -0700727 ALOGW("Unable to acquire a lockedBuffer, very likely client tries to lock more than"
728 " maxImages buffers");
Igor Murashkine3351f12013-09-13 13:08:04 -0700729 return ACQUIRE_MAX_IMAGES;
Zhijun He212e78d2013-06-07 11:36:23 -0700730 }
731 status_t res = consumer->lockNextBuffer(buffer);
732 if (res != NO_ERROR) {
lina.x.pi33477892014-01-27 10:31:44 +0800733 ctx->returnLockedBuffer(buffer);
Jeff Brownf724c272013-08-07 14:17:04 -0700734 if (res != BAD_VALUE /*no buffers*/) {
Igor Murashkindd064322013-08-14 19:05:17 -0700735 if (res == NOT_ENOUGH_DATA) {
Igor Murashkine3351f12013-09-13 13:08:04 -0700736 return ACQUIRE_MAX_IMAGES;
Igor Murashkindd064322013-08-14 19:05:17 -0700737 } else {
738 ALOGE("%s Fail to lockNextBuffer with error: %d ",
739 __FUNCTION__, res);
Igor Murashkine3351f12013-09-13 13:08:04 -0700740 jniThrowExceptionFmt(env, "java/lang/AssertionError",
Igor Murashkindd064322013-08-14 19:05:17 -0700741 "Unknown error (%d) when we tried to lock buffer.",
742 res);
743 }
Jeff Brownf724c272013-08-07 14:17:04 -0700744 }
Igor Murashkine3351f12013-09-13 13:08:04 -0700745 return ACQUIRE_NO_BUFFERS;
Zhijun He212e78d2013-06-07 11:36:23 -0700746 }
747
Zhijun He4eda9f52013-09-18 08:00:02 -0700748 if (buffer->format == HAL_PIXEL_FORMAT_YCrCb_420_SP) {
749 jniThrowException(env, "java/lang/UnsupportedOperationException",
750 "NV21 format is not supported by ImageReader");
751 return -1;
752 }
753
Zhijun He212e78d2013-06-07 11:36:23 -0700754 // Check if the left-top corner of the crop rect is origin, we currently assume this point is
755 // zero, will revist this once this assumption turns out problematic.
756 Point lt = buffer->crop.leftTop();
757 if (lt.x != 0 || lt.y != 0) {
Zhijun He4eda9f52013-09-18 08:00:02 -0700758 jniThrowExceptionFmt(env, "java/lang/UnsupportedOperationException",
759 "crop left top corner [%d, %d] need to be at origin", lt.x, lt.y);
Igor Murashkine3351f12013-09-13 13:08:04 -0700760 return -1;
Zhijun He212e78d2013-06-07 11:36:23 -0700761 }
762
763 // Check if the producer buffer configurations match what ImageReader configured.
764 // We want to fail for the very first image because this case is too bad.
Zhijun He534046d2013-07-01 11:03:41 -0700765 int outputWidth = buffer->width;
766 int outputHeight = buffer->height;
767
Zhijun He37682132013-09-10 17:50:34 -0700768 // Correct width/height when crop is set.
Zhijun He9e6d0732013-09-16 16:03:36 -0700769 if (!buffer->crop.isEmpty()) {
Zhijun Hecfa55332013-09-16 09:49:28 -0700770 outputWidth = buffer->crop.getWidth();
771 outputHeight = buffer->crop.getHeight();
Zhijun He534046d2013-07-01 11:03:41 -0700772 }
773
Zhijun He212e78d2013-06-07 11:36:23 -0700774 int imageReaderWidth = ctx->getBufferWidth();
775 int imageReaderHeight = ctx->getBufferHeight();
Zhijun He37682132013-09-10 17:50:34 -0700776 if ((buffer->format != HAL_PIXEL_FORMAT_BLOB) &&
777 (imageReaderWidth != outputWidth || imageReaderHeight > outputHeight)) {
778 /**
779 * For video decoder, the buffer height is actually the vertical stride,
780 * which is always >= actual image height. For future, decoder need provide
781 * right crop rectangle to CpuConsumer to indicate the actual image height,
782 * see bug 9563986. After this bug is fixed, we can enforce the height equal
783 * check. Right now, only make sure buffer height is no less than ImageReader
784 * height.
785 */
786 jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
787 "Producer buffer size: %dx%d, doesn't match ImageReader configured size: %dx%d",
788 outputWidth, outputHeight, imageReaderWidth, imageReaderHeight);
Igor Murashkine3351f12013-09-13 13:08:04 -0700789 return -1;
Zhijun He212e78d2013-06-07 11:36:23 -0700790 }
791
Ruben Brunkfeb50af2014-05-09 19:58:49 -0700792 int imgReaderFmt = ctx->getBufferFormat();
793 int bufFmt = buffer->format;
794 if (imgReaderFmt != bufFmt) {
Ruben Brunk91b9aab2014-06-20 00:24:56 -0700795 // Special casing for when producer switches to a format compatible with flexible YUV
796 // (HAL_PIXEL_FORMAT_YCbCr_420_888).
797 if (imgReaderFmt == HAL_PIXEL_FORMAT_YCbCr_420_888 && (bufFmt ==
798 HAL_PIXEL_FORMAT_YCrCb_420_SP || bufFmt == HAL_PIXEL_FORMAT_YV12)) {
799 ctx->setBufferFormat(bufFmt);
800 ALOGV("%s: Overriding buffer format YUV_420_888 to %x.", __FUNCTION__, bufFmt);
Ruben Brunkfeb50af2014-05-09 19:58:49 -0700801 } else {
802 // Return the buffer to the queue.
803 consumer->unlockBuffer(*buffer);
804 ctx->returnLockedBuffer(buffer);
Zhijun He212e78d2013-06-07 11:36:23 -0700805
Ruben Brunkfeb50af2014-05-09 19:58:49 -0700806 // Throw exception
807 ALOGE("Producer output buffer format: 0x%x, ImageReader configured format: 0x%x",
808 buffer->format, ctx->getBufferFormat());
809 String8 msg;
810 msg.appendFormat("The producer output buffer format 0x%x doesn't "
811 "match the ImageReader's configured buffer format 0x%x.",
812 buffer->format, ctx->getBufferFormat());
813 jniThrowException(env, "java/lang/UnsupportedOperationException",
814 msg.string());
815 return -1;
816 }
Zhijun He212e78d2013-06-07 11:36:23 -0700817 }
818 // Set SurfaceImage instance member variables
819 Image_setBuffer(env, image, buffer);
Jeff Brownef961212013-08-05 20:39:29 -0700820 env->SetLongField(image, gSurfaceImageClassInfo.mTimestamp,
821 static_cast<jlong>(buffer->timestamp));
Zhijun He212e78d2013-06-07 11:36:23 -0700822
Igor Murashkine3351f12013-09-13 13:08:04 -0700823 return ACQUIRE_SUCCESS;
Zhijun He212e78d2013-06-07 11:36:23 -0700824}
825
826static jobject ImageReader_getSurface(JNIEnv* env, jobject thiz)
827{
828 ALOGV("%s: ", __FUNCTION__);
829
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700830 IGraphicBufferProducer* gbp = ImageReader_getProducer(env, thiz);
831 if (gbp == NULL) {
Zhijun He212e78d2013-06-07 11:36:23 -0700832 jniThrowRuntimeException(env, "CpuConsumer is uninitialized");
833 return NULL;
834 }
835
836 // Wrap the IGBP in a Java-language Surface.
Dan Stoza5b3c7c12014-03-12 16:44:45 -0700837 return android_view_Surface_createFromIGraphicBufferProducer(env, gbp);
Zhijun He212e78d2013-06-07 11:36:23 -0700838}
839
840static jobject Image_createSurfacePlane(JNIEnv* env, jobject thiz, int idx)
841{
842 int rowStride, pixelStride;
843 ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
844
845 CpuConsumer::LockedBuffer* buffer = Image_getLockedBuffer(env, thiz);
846
847 ALOG_ASSERT(buffer != NULL);
848 if (buffer == NULL) {
849 jniThrowException(env, "java/lang/IllegalStateException", "Image was released");
850 }
851 rowStride = Image_imageGetRowStride(env, buffer, idx);
852 pixelStride = Image_imageGetPixelStride(env, buffer, idx);
853
Jeff Brownef961212013-08-05 20:39:29 -0700854 jobject surfPlaneObj = env->NewObject(gSurfacePlaneClassInfo.clazz,
855 gSurfacePlaneClassInfo.ctor, thiz, idx, rowStride, pixelStride);
Zhijun He212e78d2013-06-07 11:36:23 -0700856
857 return surfPlaneObj;
858}
859
860static jobject Image_getByteBuffer(JNIEnv* env, jobject thiz, int idx)
861{
862 uint8_t *base = NULL;
863 uint32_t size = 0;
864 jobject byteBuffer;
865
866 ALOGV("%s: buffer index: %d", __FUNCTION__, idx);
867
868 CpuConsumer::LockedBuffer* buffer = Image_getLockedBuffer(env, thiz);
869
870 if (buffer == NULL) {
871 jniThrowException(env, "java/lang/IllegalStateException", "Image was released");
872 }
873
874 // Create byteBuffer from native buffer
875 Image_getLockedBufferInfo(env, buffer, idx, &base, &size);
Igor Murashkin5096def2014-06-24 10:49:11 -0700876
877 if (size > static_cast<uint32_t>(INT32_MAX)) {
878 // Byte buffer have 'int capacity', so check the range
879 jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
880 "Size too large for bytebuffer capacity " PRIu32, size);
881 return NULL;
882 }
883
Zhijun He212e78d2013-06-07 11:36:23 -0700884 byteBuffer = env->NewDirectByteBuffer(base, size);
885 // TODO: throw dvm exOutOfMemoryError?
886 if ((byteBuffer == NULL) && (env->ExceptionCheck() == false)) {
887 jniThrowException(env, "java/lang/IllegalStateException", "Failed to allocate ByteBuffer");
888 }
889
890 return byteBuffer;
891}
892
893} // extern "C"
894
895// ----------------------------------------------------------------------------
896
897static JNINativeMethod gImageReaderMethods[] = {
898 {"nativeClassInit", "()V", (void*)ImageReader_classInit },
899 {"nativeInit", "(Ljava/lang/Object;IIII)V", (void*)ImageReader_init },
900 {"nativeClose", "()V", (void*)ImageReader_close },
901 {"nativeReleaseImage", "(Landroid/media/Image;)V", (void*)ImageReader_imageRelease },
Igor Murashkine3351f12013-09-13 13:08:04 -0700902 {"nativeImageSetup", "(Landroid/media/Image;)I", (void*)ImageReader_imageSetup },
Zhijun He212e78d2013-06-07 11:36:23 -0700903 {"nativeGetSurface", "()Landroid/view/Surface;", (void*)ImageReader_getSurface },
904};
905
906static JNINativeMethod gImageMethods[] = {
907 {"nativeImageGetBuffer", "(I)Ljava/nio/ByteBuffer;", (void*)Image_getByteBuffer },
908 {"nativeCreatePlane", "(I)Landroid/media/ImageReader$SurfaceImage$SurfacePlane;",
909 (void*)Image_createSurfacePlane },
910};
911
912int register_android_media_ImageReader(JNIEnv *env) {
913
914 int ret1 = AndroidRuntime::registerNativeMethods(env,
915 "android/media/ImageReader", gImageReaderMethods, NELEM(gImageReaderMethods));
916
917 int ret2 = AndroidRuntime::registerNativeMethods(env,
918 "android/media/ImageReader$SurfaceImage", gImageMethods, NELEM(gImageMethods));
919
920 return (ret1 || ret2);
921}