android_media_MediaRecorder.cpp revision 4935d05eaa306cef88cf0ab13eca386f270409ec
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 <ui/SurfaceComposerClient.h>
22#include <ui/ICameraService.h>
23#include <ui/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
39using namespace android;
40
41// ----------------------------------------------------------------------------
42
43// helper function to extract a native Camera object from a Camera Java object
44extern sp<Camera> get_native_camera(JNIEnv *env, jobject thiz, struct JNICameraContext** context);
45
46struct 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};
54static fields_t fields;
55
56static Mutex sLock;
57
58// ----------------------------------------------------------------------------
59// ref-counted object for callbacks
60class JNIMediaRecorderListener: public MediaRecorderListener
61{
62public:
63    JNIMediaRecorderListener(JNIEnv* env, jobject thiz, jobject weak_thiz);
64    ~JNIMediaRecorderListener();
65    void notify(int msg, int ext1, int ext2);
66private:
67    JNIMediaRecorderListener();
68    jclass      mClass;     // Reference to MediaRecorder class
69    jobject     mObject;    // Weak ref to MediaRecorder Java object to call on
70};
71
72JNIMediaRecorderListener::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
90JNIMediaRecorderListener::~JNIMediaRecorderListener()
91{
92    // remove global references
93    JNIEnv *env = AndroidRuntime::getJNIEnv();
94    env->DeleteGlobalRef(mObject);
95    env->DeleteGlobalRef(mClass);
96}
97
98void 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
108static 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.
116static 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
129static 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
136static 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
151static 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
164static void
165android_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
176static void
177android_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
189static void
190android_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
201static void
202android_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
213static void
214android_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
225static void
226android_media_MediaRecorder_setParameters(JNIEnv *env, jobject thiz, jstring params)
227{
228    LOGV("setParameters()");
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
248static void
249android_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
262static void
263android_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
275static void
276android_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
287static void
288android_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
299static void
300android_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
312static void
313android_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        LOGI("prepare: surface=%p (id=%d)", native_surface.get(), native_surface->ID());
322        if (process_media_recorder_call(env, mr->setPreviewSurface(native_surface), "java/lang/RuntimeException", "setPreviewSurface failed.")) {
323            return;
324        }
325    }
326    process_media_recorder_call(env, mr->prepare(), "java/io/IOException", "prepare failed.");
327}
328
329static int
330android_media_MediaRecorder_native_getMaxAmplitude(JNIEnv *env, jobject thiz)
331{
332    LOGV("getMaxAmplitude");
333    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
334    int result = 0;
335    process_media_recorder_call(env, mr->getMaxAmplitude(&result), "java/lang/RuntimeException", "getMaxAmplitude failed.");
336    return result;
337}
338
339static void
340android_media_MediaRecorder_start(JNIEnv *env, jobject thiz)
341{
342    LOGV("start");
343    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
344    process_media_recorder_call(env, mr->start(), "java/lang/RuntimeException", "start failed.");
345}
346
347static void
348android_media_MediaRecorder_stop(JNIEnv *env, jobject thiz)
349{
350    LOGV("stop");
351    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
352    process_media_recorder_call(env, mr->stop(), "java/lang/RuntimeException", "stop failed.");
353}
354
355static void
356android_media_MediaRecorder_native_reset(JNIEnv *env, jobject thiz)
357{
358    LOGV("native_reset");
359    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
360    process_media_recorder_call(env, mr->reset(), "java/lang/RuntimeException", "native_reset failed.");
361}
362
363static void
364android_media_MediaRecorder_release(JNIEnv *env, jobject thiz)
365{
366    LOGV("release");
367    sp<MediaRecorder> mr = setMediaRecorder(env, thiz, 0);
368    if (mr != NULL) {
369        mr->setListener(NULL);
370        mr->release();
371    }
372}
373
374// This function gets some field IDs, which in turn causes class initialization.
375// It is called from a static block in MediaRecorder, which won't run until the
376// first time an instance of this class is used.
377static void
378android_media_MediaRecorder_native_init(JNIEnv *env)
379{
380    jclass clazz;
381
382    clazz = env->FindClass("android/media/MediaRecorder");
383    if (clazz == NULL) {
384        jniThrowException(env, "java/lang/RuntimeException", "Can't find android/media/MediaRecorder");
385        return;
386    }
387
388    fields.context = env->GetFieldID(clazz, "mNativeContext", "I");
389    if (fields.context == NULL) {
390        jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaRecorder.mNativeContext");
391        return;
392    }
393
394    fields.surface = env->GetFieldID(clazz, "mSurface", "Landroid/view/Surface;");
395    if (fields.surface == NULL) {
396        jniThrowException(env, "java/lang/RuntimeException", "Can't find MediaRecorder.mSurface");
397        return;
398    }
399
400    jclass surface = env->FindClass("android/view/Surface");
401    if (surface == NULL) {
402        jniThrowException(env, "java/lang/RuntimeException", "Can't find android/view/Surface");
403        return;
404    }
405
406    fields.surface_native = env->GetFieldID(surface, "mSurface", "I");
407    if (fields.surface_native == NULL) {
408        jniThrowException(env, "java/lang/RuntimeException", "Can't find Surface.mSurface");
409        return;
410    }
411
412    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
413                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
414    if (fields.post_event == NULL) {
415        jniThrowException(env, "java/lang/RuntimeException", "MediaRecorder.postEventFromNative");
416        return;
417    }
418}
419
420
421static void
422android_media_MediaRecorder_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
423{
424    LOGV("setup");
425    sp<MediaRecorder> mr = new MediaRecorder();
426    if (mr == NULL) {
427        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
428        return;
429    }
430    if (mr->initCheck() != NO_ERROR) {
431        jniThrowException(env, "java/lang/IOException", "Unable to initialize camera");
432        return;
433    }
434
435    // create new listener and give it to MediaRecorder
436    sp<JNIMediaRecorderListener> listener = new JNIMediaRecorderListener(env, thiz, weak_this);
437    mr->setListener(listener);
438
439    setMediaRecorder(env, thiz, mr);
440}
441
442static void
443android_media_MediaRecorder_native_finalize(JNIEnv *env, jobject thiz)
444{
445    LOGV("finalize");
446    android_media_MediaRecorder_release(env, thiz);
447}
448
449// ----------------------------------------------------------------------------
450
451static JNINativeMethod gMethods[] = {
452    {"setCamera",            "(Landroid/hardware/Camera;)V",    (void *)android_media_MediaRecorder_setCamera},
453    {"setVideoSource",       "(I)V",                            (void *)android_media_MediaRecorder_setVideoSource},
454    {"setAudioSource",       "(I)V",                            (void *)android_media_MediaRecorder_setAudioSource},
455    {"setOutputFormat",      "(I)V",                            (void *)android_media_MediaRecorder_setOutputFormat},
456    {"setVideoEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setVideoEncoder},
457    {"setAudioEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setAudioEncoder},
458    {"setParameters",        "(Ljava/lang/String;)V",           (void *)android_media_MediaRecorder_setParameters},
459    {"_setOutputFile",       "(Ljava/io/FileDescriptor;JJ)V",   (void *)android_media_MediaRecorder_setOutputFileFD},
460    {"setVideoSize",         "(II)V",                           (void *)android_media_MediaRecorder_setVideoSize},
461    {"setVideoFrameRate",    "(I)V",                            (void *)android_media_MediaRecorder_setVideoFrameRate},
462    {"setMaxDuration",       "(I)V",                            (void *)android_media_MediaRecorder_setMaxDuration},
463    {"setMaxFileSize",       "(J)V",                            (void *)android_media_MediaRecorder_setMaxFileSize},
464    {"_prepare",             "()V",                             (void *)android_media_MediaRecorder_prepare},
465    {"getMaxAmplitude",      "()I",                             (void *)android_media_MediaRecorder_native_getMaxAmplitude},
466    {"start",                "()V",                             (void *)android_media_MediaRecorder_start},
467    {"stop",                 "()V",                             (void *)android_media_MediaRecorder_stop},
468    {"native_reset",         "()V",                             (void *)android_media_MediaRecorder_native_reset},
469    {"release",              "()V",                             (void *)android_media_MediaRecorder_release},
470    {"native_init",          "()V",                             (void *)android_media_MediaRecorder_native_init},
471    {"native_setup",         "(Ljava/lang/Object;)V",           (void *)android_media_MediaRecorder_native_setup},
472    {"native_finalize",      "()V",                             (void *)android_media_MediaRecorder_native_finalize},
473};
474
475static const char* const kClassPathName = "android/media/MediaRecorder";
476
477// This function only registers the native methods, and is called from
478// JNI_OnLoad in android_media_MediaPlayer.cpp
479int register_android_media_MediaRecorder(JNIEnv *env)
480{
481    return AndroidRuntime::registerNativeMethods(env,
482                "android/media/MediaRecorder", gMethods, NELEM(gMethods));
483}
484
485
486