Home | History | Annotate | Download | only in jni
      1 /*
      2  * Copyright (C) 2008 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 "MediaRecorderJNI"
     19 #include <utils/Log.h>
     20 
     21 #include <surfaceflinger/SurfaceComposerClient.h>
     22 #include <camera/ICameraService.h>
     23 #include <camera/Camera.h>
     24 #include <media/mediarecorder.h>
     25 #include <stdio.h>
     26 #include <assert.h>
     27 #include <limits.h>
     28 #include <unistd.h>
     29 #include <fcntl.h>
     30 #include <utils/threads.h>
     31 
     32 #include "jni.h"
     33 #include "JNIHelp.h"
     34 #include "android_runtime/AndroidRuntime.h"
     35 
     36 
     37 // ----------------------------------------------------------------------------
     38 
     39 using namespace android;
     40 
     41 // ----------------------------------------------------------------------------
     42 
     43 // helper function to extract a native Camera object from a Camera Java object
     44 extern sp<Camera> get_native_camera(JNIEnv *env, jobject thiz, struct JNICameraContext** context);
     45 
     46 struct fields_t {
     47     jfieldID    context;
     48     jfieldID    surface;
     49     /* actually in android.view.Surface XXX */
     50     jfieldID    surface_native;
     51 
     52     jmethodID   post_event;
     53 };
     54 static fields_t fields;
     55 
     56 static Mutex sLock;
     57 
     58 // ----------------------------------------------------------------------------
     59 // ref-counted object for callbacks
     60 class JNIMediaRecorderListener: public MediaRecorderListener
     61 {
     62 public:
     63     JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz);
     64     ~JNIMediaRecorderListener();
     65     void notify(int msg, int ext1, int ext2);
     66 private:
     67     JNIMediaRecorderListener();
     68     jclass      mClass;     // Reference to MediaRecorder class
     69     jobject     mObject;    // Weak ref to MediaRecorder Java object to call on
     70 };
     71 
     72 JNIMediaRecorderListener::JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz)
     73 {
     74 
     75     // Hold onto the MediaRecorder class for use in calling the static method
     76     // that posts events to the application thread.
     77     jclass clazz = env->GetObjectClass(thiz);
     78     if (clazz == NULL) {
     79         LOGE("Can't find android/media/MediaRecorder");
     80         jniThrowException(env, "java/lang/Exception", NULL);
     81         return;
     82     }
     83     mClass = (jclass)env->NewGlobalRef(clazz);
     84 
     85     // We use a weak reference so the MediaRecorder object can be garbage collected.
     86     // The reference is only used as a proxy for callbacks.
     87     mObject  = env->NewGlobalRef(weak_thiz);
     88 }
     89 
     90 JNIMediaRecorderListener::~JNIMediaRecorderListener()
     91 {
     92     // remove global references
     93     JNIEnv *env = AndroidRuntime::getJNIEnv();
     94     env->DeleteGlobalRef(mObject);
     95     env->DeleteGlobalRef(mClass);
     96 }
     97 
     98 void JNIMediaRecorderListener::notify(int msg, int ext1, int ext2)
     99 {
    100     LOGV("JNIMediaRecorderListener::notify");
    101 
    102     JNIEnv *env = AndroidRuntime::getJNIEnv();
    103     env->CallStaticVoidMethod(mClass, fields.post_event, mObject, msg, ext1, ext2, 0);
    104 }
    105 
    106 // ----------------------------------------------------------------------------
    107 
    108 static sp<Surface> get_surface(JNIEnv* env, jobject clazz)
    109 {
    110     LOGV("get_surface");
    111     Surface* const p = (Surface*)env->GetIntField(clazz, fields.surface_native);
    112     return sp<Surface>(p);
    113 }
    114 
    115 // Returns true if it throws an exception.
    116 static bool process_media_recorder_call(JNIEnv *env, status_t opStatus, const char* exception, const char* message)
    117 {
    118     LOGV("process_media_recorder_call");
    119     if (opStatus == (status_t)INVALID_OPERATION) {
    120         jniThrowException(env, "java/lang/IllegalStateException", NULL);
    121         return true;
    122     } else if (opStatus != (status_t)OK) {
    123         jniThrowException(env, exception, message);
    124         return true;
    125     }
    126     return false;
    127 }
    128 
    129 static sp<MediaRecorder> getMediaRecorder(JNIEnv* env, jobject thiz)
    130 {
    131     Mutex::Autolock l(sLock);
    132     MediaRecorder* const p = (MediaRecorder*)env->GetIntField(thiz, fields.context);
    133     return sp<MediaRecorder>(p);
    134 }
    135 
    136 static sp<MediaRecorder> setMediaRecorder(JNIEnv* env, jobject thiz, const sp<MediaRecorder>& recorder)
    137 {
    138     Mutex::Autolock l(sLock);
    139     sp<MediaRecorder> old = (MediaRecorder*)env->GetIntField(thiz, fields.context);
    140     if (recorder.get()) {
    141         recorder->incStrong(thiz);
    142     }
    143     if (old != 0) {
    144         old->decStrong(thiz);
    145     }
    146     env->SetIntField(thiz, fields.context, (int)recorder.get());
    147     return old;
    148 }
    149 
    150 
    151 static void android_media_MediaRecorder_setCamera(JNIEnv* env, jobject thiz, jobject camera)
    152 {
    153     // we should not pass a null camera to get_native_camera() call.
    154     if (camera == NULL) {
    155         jniThrowException(env, "java/lang/NullPointerException", "camera object is a NULL pointer");
    156         return;
    157     }
    158     sp<Camera> c = get_native_camera(env, camera, NULL);
    159     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    160     process_media_recorder_call(env, mr->setCamera(c->remote()),
    161             "java/lang/RuntimeException", "setCamera failed.");
    162 }
    163 
    164 static void
    165 android_media_MediaRecorder_setVideoSource(JNIEnv *env, jobject thiz, jint vs)
    166 {
    167     LOGV("setVideoSource(%d)", vs);
    168     if (vs < VIDEO_SOURCE_DEFAULT || vs >= VIDEO_SOURCE_LIST_END) {
    169         jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video source");
    170         return;
    171     }
    172     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    173     process_media_recorder_call(env, mr->setVideoSource(vs), "java/lang/RuntimeException", "setVideoSource failed.");
    174 }
    175 
    176 static void
    177 android_media_MediaRecorder_setAudioSource(JNIEnv *env, jobject thiz, jint as)
    178 {
    179     LOGV("setAudioSource(%d)", as);
    180     if (as < AUDIO_SOURCE_DEFAULT || as >= AUDIO_SOURCE_LIST_END) {
    181         jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio source");
    182         return;
    183     }
    184 
    185     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    186     process_media_recorder_call(env, mr->setAudioSource(as), "java/lang/RuntimeException", "setAudioSource failed.");
    187 }
    188 
    189 static void
    190 android_media_MediaRecorder_setOutputFormat(JNIEnv *env, jobject thiz, jint of)
    191 {
    192     LOGV("setOutputFormat(%d)", of);
    193     if (of < OUTPUT_FORMAT_DEFAULT || of >= OUTPUT_FORMAT_LIST_END) {
    194         jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid output format");
    195         return;
    196     }
    197     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    198     process_media_recorder_call(env, mr->setOutputFormat(of), "java/lang/RuntimeException", "setOutputFormat failed.");
    199 }
    200 
    201 static void
    202 android_media_MediaRecorder_setVideoEncoder(JNIEnv *env, jobject thiz, jint ve)
    203 {
    204     LOGV("setVideoEncoder(%d)", ve);
    205     if (ve < VIDEO_ENCODER_DEFAULT || ve >= VIDEO_ENCODER_LIST_END) {
    206         jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video encoder");
    207         return;
    208     }
    209     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    210     process_media_recorder_call(env, mr->setVideoEncoder(ve), "java/lang/RuntimeException", "setVideoEncoder failed.");
    211 }
    212 
    213 static void
    214 android_media_MediaRecorder_setAudioEncoder(JNIEnv *env, jobject thiz, jint ae)
    215 {
    216     LOGV("setAudioEncoder(%d)", ae);
    217     if (ae < AUDIO_ENCODER_DEFAULT || ae >= AUDIO_ENCODER_LIST_END) {
    218         jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio encoder");
    219         return;
    220     }
    221     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    222     process_media_recorder_call(env, mr->setAudioEncoder(ae), "java/lang/RuntimeException", "setAudioEncoder failed.");
    223 }
    224 
    225 static void
    226 android_media_MediaRecorder_setParameter(JNIEnv *env, jobject thiz, jstring params)
    227 {
    228     LOGV("setParameter()");
    229     if (params == NULL)
    230     {
    231         LOGE("Invalid or empty params string.  This parameter will be ignored.");
    232         return;
    233     }
    234 
    235     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    236 
    237     const char* params8 = env->GetStringUTFChars(params, NULL);
    238     if (params8 == NULL)
    239     {
    240         LOGE("Failed to covert jstring to String8.  This parameter will be ignored.");
    241         return;
    242     }
    243 
    244     process_media_recorder_call(env, mr->setParameters(String8(params8)), "java/lang/RuntimeException", "setParameter failed.");
    245     env->ReleaseStringUTFChars(params,params8);
    246 }
    247 
    248 static void
    249 android_media_MediaRecorder_setOutputFileFD(JNIEnv *env, jobject thiz, jobject fileDescriptor, jlong offset, jlong length)
    250 {
    251     LOGV("setOutputFile");
    252     if (fileDescriptor == NULL) {
    253         jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
    254         return;
    255     }
    256     int fd = getParcelFileDescriptorFD(env, fileDescriptor);
    257     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    258     status_t opStatus = mr->setOutputFile(fd, offset, length);
    259     process_media_recorder_call(env, opStatus, "java/io/IOException", "setOutputFile failed.");
    260 }
    261 
    262 static void
    263 android_media_MediaRecorder_setVideoSize(JNIEnv *env, jobject thiz, jint width, jint height)
    264 {
    265     LOGV("setVideoSize(%d, %d)", width, height);
    266     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    267 
    268     if (width <= 0 || height <= 0) {
    269         jniThrowException(env, "java/lang/IllegalArgumentException", "invalid video size");
    270         return;
    271     }
    272     process_media_recorder_call(env, mr->setVideoSize(width, height), "java/lang/RuntimeException", "setVideoSize failed.");
    273 }
    274 
    275 static void
    276 android_media_MediaRecorder_setVideoFrameRate(JNIEnv *env, jobject thiz, jint rate)
    277 {
    278     LOGV("setVideoFrameRate(%d)", rate);
    279     if (rate <= 0) {
    280         jniThrowException(env, "java/lang/IllegalArgumentException", "invalid frame rate");
    281         return;
    282     }
    283     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    284     process_media_recorder_call(env, mr->setVideoFrameRate(rate), "java/lang/RuntimeException", "setVideoFrameRate failed.");
    285 }
    286 
    287 static void
    288 android_media_MediaRecorder_setMaxDuration(JNIEnv *env, jobject thiz, jint max_duration_ms)
    289 {
    290     LOGV("setMaxDuration(%d)", max_duration_ms);
    291     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    292 
    293     char params[64];
    294     sprintf(params, "max-duration=%d", max_duration_ms);
    295 
    296     process_media_recorder_call(env, mr->setParameters(String8(params)), "java/lang/RuntimeException", "setMaxDuration failed.");
    297 }
    298 
    299 static void
    300 android_media_MediaRecorder_setMaxFileSize(
    301         JNIEnv *env, jobject thiz, jlong max_filesize_bytes)
    302 {
    303     LOGV("setMaxFileSize(%lld)", max_filesize_bytes);
    304     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    305 
    306     char params[64];
    307     sprintf(params, "max-filesize=%lld", max_filesize_bytes);
    308 
    309     process_media_recorder_call(env, mr->setParameters(String8(params)), "java/lang/RuntimeException", "setMaxFileSize failed.");
    310 }
    311 
    312 static void
    313 android_media_MediaRecorder_prepare(JNIEnv *env, jobject thiz)
    314 {
    315     LOGV("prepare");
    316     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    317 
    318     jobject surface = env->GetObjectField(thiz, fields.surface);
    319     if (surface != NULL) {
    320         const sp<Surface> native_surface = get_surface(env, surface);
    321 
    322         // The application may misbehave and
    323         // the preview surface becomes unavailable
    324         if (native_surface.get() == 0) {
    325             LOGE("Application lost the surface");
    326             jniThrowException(env, "java/io/IOException", "invalid preview surface");
    327             return;
    328         }
    329 
    330         LOGI("prepare: surface=%p (identity=%d)", native_surface.get(), native_surface->getIdentity());
    331         if (process_media_recorder_call(env, mr->setPreviewSurface(native_surface), "java/lang/RuntimeException", "setPreviewSurface failed.")) {
    332             return;
    333         }
    334     }
    335     process_media_recorder_call(env, mr->prepare(), "java/io/IOException", "prepare failed.");
    336 }
    337 
    338 static int
    339 android_media_MediaRecorder_native_getMaxAmplitude(JNIEnv *env, jobject thiz)
    340 {
    341     LOGV("getMaxAmplitude");
    342     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    343     int result = 0;
    344     process_media_recorder_call(env, mr->getMaxAmplitude(&result), "java/lang/RuntimeException", "getMaxAmplitude failed.");
    345     return result;
    346 }
    347 
    348 static void
    349 android_media_MediaRecorder_start(JNIEnv *env, jobject thiz)
    350 {
    351     LOGV("start");
    352     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    353     process_media_recorder_call(env, mr->start(), "java/lang/RuntimeException", "start failed.");
    354 }
    355 
    356 static void
    357 android_media_MediaRecorder_stop(JNIEnv *env, jobject thiz)
    358 {
    359     LOGV("stop");
    360     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    361     process_media_recorder_call(env, mr->stop(), "java/lang/RuntimeException", "stop failed.");
    362 }
    363 
    364 static void
    365 android_media_MediaRecorder_native_reset(JNIEnv *env, jobject thiz)
    366 {
    367     LOGV("native_reset");
    368     sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
    369     process_media_recorder_call(env, mr->reset(), "java/lang/RuntimeException", "native_reset failed.");
    370 }
    371 
    372 static void
    373 android_media_MediaRecorder_release(JNIEnv *env, jobject thiz)
    374 {
    375     LOGV("release");
    376     sp<MediaRecorder> mr = setMediaRecorder(env, thiz, 0);
    377     if (mr != NULL) {
    378         mr->setListener(NULL);
    379         mr->release();
    380     }
    381 }
    382 
    383 // This function gets some field IDs, which in turn causes class initialization.
    384 // It is called from a static block in MediaRecorder, which won't run until the
    385 // first time an instance of this class is used.
    386 static void
    387 android_media_MediaRecorder_native_init(JNIEnv *env)
    388 {
    389     jclass clazz;
    390 
    391     clazz = env->FindClass("android/media/MediaRecorder");
    392     if (clazz == NULL) {
    393         jniThrowException(env, "java/lang/RuntimeException", "Can't find android/media/MediaRecorder");
    394         return;
    395     }
    396 
    397     fields.context = env->GetFieldID(clazz, "mNativeContext", "I");
    398     if (fields.context == NULL) {
    399         jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaRecorder.mNativeContext");
    400         return;
    401     }
    402 
    403     fields.surface = env->GetFieldID(clazz, "mSurface", "Landroid/view/Surface;");
    404     if (fields.surface == NULL) {
    405         jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaRecorder.mSurface");
    406         return;
    407     }
    408 
    409     jclass surface = env->FindClass("android/view/Surface");
    410     if (surface == NULL) {
    411         jniThrowException(env, "java/lang/RuntimeException", "Can't find android/view/Surface");
    412         return;
    413     }
    414 
    415     fields.surface_native = env->GetFieldID(surface, ANDROID_VIEW_SURFACE_JNI_ID, "I");
    416     if (fields.surface_native == NULL) {
    417         jniThrowException(env, "java/lang/RuntimeException", "Can't find Surface.mSurface");
    418         return;
    419     }
    420 
    421     fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
    422                                                "(Ljava/lang/Object;IIILjava/lang/Object;)V");
    423     if (fields.post_event == NULL) {
    424         jniThrowException(env, "java/lang/RuntimeException", "MediaRecorder.postEventFromNative");
    425         return;
    426     }
    427 }
    428 
    429 
    430 static void
    431 android_media_MediaRecorder_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
    432 {
    433     LOGV("setup");
    434     sp<MediaRecorder> mr = new MediaRecorder();
    435     if (mr == NULL) {
    436         jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
    437         return;
    438     }
    439     if (mr->initCheck() != NO_ERROR) {
    440         jniThrowException(env, "java/lang/RuntimeException", "Unable to initialize media recorder");
    441         return;
    442     }
    443 
    444     // create new listener and give it to MediaRecorder
    445     sp<JNIMediaRecorderListener> listener = new JNIMediaRecorderListener(env, thiz, weak_this);
    446     mr->setListener(listener);
    447 
    448     setMediaRecorder(env, thiz, mr);
    449 }
    450 
    451 static void
    452 android_media_MediaRecorder_native_finalize(JNIEnv *env, jobject thiz)
    453 {
    454     LOGV("finalize");
    455     android_media_MediaRecorder_release(env, thiz);
    456 }
    457 
    458 // ----------------------------------------------------------------------------
    459 
    460 static JNINativeMethod gMethods[] = {
    461     {"setCamera",            "(Landroid/hardware/Camera;)V",    (void *)android_media_MediaRecorder_setCamera},
    462     {"setVideoSource",       "(I)V",                            (void *)android_media_MediaRecorder_setVideoSource},
    463     {"setAudioSource",       "(I)V",                            (void *)android_media_MediaRecorder_setAudioSource},
    464     {"setOutputFormat",      "(I)V",                            (void *)android_media_MediaRecorder_setOutputFormat},
    465     {"setVideoEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setVideoEncoder},
    466     {"setAudioEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setAudioEncoder},
    467     {"setParameter",         "(Ljava/lang/String;)V",           (void *)android_media_MediaRecorder_setParameter},
    468     {"_setOutputFile",       "(Ljava/io/FileDescriptor;JJ)V",   (void *)android_media_MediaRecorder_setOutputFileFD},
    469     {"setVideoSize",         "(II)V",                           (void *)android_media_MediaRecorder_setVideoSize},
    470     {"setVideoFrameRate",    "(I)V",                            (void *)android_media_MediaRecorder_setVideoFrameRate},
    471     {"setMaxDuration",       "(I)V",                            (void *)android_media_MediaRecorder_setMaxDuration},
    472     {"setMaxFileSize",       "(J)V",                            (void *)android_media_MediaRecorder_setMaxFileSize},
    473     {"_prepare",             "()V",                             (void *)android_media_MediaRecorder_prepare},
    474     {"getMaxAmplitude",      "()I",                             (void *)android_media_MediaRecorder_native_getMaxAmplitude},
    475     {"start",                "()V",                             (void *)android_media_MediaRecorder_start},
    476     {"stop",                 "()V",                             (void *)android_media_MediaRecorder_stop},
    477     {"native_reset",         "()V",                             (void *)android_media_MediaRecorder_native_reset},
    478     {"release",              "()V",                             (void *)android_media_MediaRecorder_release},
    479     {"native_init",          "()V",                             (void *)android_media_MediaRecorder_native_init},
    480     {"native_setup",         "(Ljava/lang/Object;)V",           (void *)android_media_MediaRecorder_native_setup},
    481     {"native_finalize",      "()V",                             (void *)android_media_MediaRecorder_native_finalize},
    482 };
    483 
    484 static const char* const kClassPathName = "android/media/MediaRecorder";
    485 
    486 // This function only registers the native methods, and is called from
    487 // JNI_OnLoad in android_media_MediaPlayer.cpp
    488 int register_android_media_MediaRecorder(JNIEnv *env)
    489 {
    490     return AndroidRuntime::registerNativeMethods(env,
    491                 "android/media/MediaRecorder", gMethods, NELEM(gMethods));
    492 }
    493 
    494 
    495