android_media_MediaRecorder.cpp revision 3dec7d563a2f3e1eb967ce2054a00b6620e3558c
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 camera_context_t** 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    sp<Camera> c = get_native_camera(env, camera, NULL);
154    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
155    process_media_recorder_call(env, mr->setCamera(c->remote()),
156            "java/lang/RuntimeException", "setCamera failed.");
157}
158
159static void
160android_media_MediaRecorder_setVideoSource(JNIEnv *env, jobject thiz, jint vs)
161{
162    LOGV("setVideoSource(%d)", vs);
163    if (vs < VIDEO_SOURCE_DEFAULT || vs > VIDEO_SOURCE_CAMERA) {
164        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video source");
165        return;
166    }
167    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
168    process_media_recorder_call(env, mr->setVideoSource(vs), "java/lang/RuntimeException", "setVideoSource failed.");
169}
170
171static void
172android_media_MediaRecorder_setAudioSource(JNIEnv *env, jobject thiz, jint as)
173{
174    LOGV("setAudioSource(%d)", as);
175    if (as < AUDIO_SOURCE_DEFAULT || as > AUDIO_SOURCE_MIC) {
176        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio source");
177        return;
178    }
179    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
180    process_media_recorder_call(env, mr->setAudioSource(as), "java/lang/RuntimeException", "setAudioSource failed.");
181}
182
183static void
184android_media_MediaRecorder_setOutputFormat(JNIEnv *env, jobject thiz, jint of)
185{
186    LOGV("setOutputFormat(%d)", of);
187    if (of < OUTPUT_FORMAT_DEFAULT || of >= OUTPUT_FORMAT_LIST_END) {
188        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid output format");
189        return;
190    }
191    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
192    process_media_recorder_call(env, mr->setOutputFormat(of), "java/lang/RuntimeException", "setOutputFormat failed.");
193}
194
195static void
196android_media_MediaRecorder_setVideoEncoder(JNIEnv *env, jobject thiz, jint ve)
197{
198    LOGV("setVideoEncoder(%d)", ve);
199    if (ve < VIDEO_ENCODER_DEFAULT || ve > VIDEO_ENCODER_MPEG_4_SP) {
200        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid video encoder");
201        return;
202    }
203    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
204    process_media_recorder_call(env, mr->setVideoEncoder(ve), "java/lang/RuntimeException", "setVideoEncoder failed.");
205}
206
207static void
208android_media_MediaRecorder_setAudioEncoder(JNIEnv *env, jobject thiz, jint ae)
209{
210    LOGV("setAudioEncoder(%d)", ae);
211    if (ae < AUDIO_ENCODER_DEFAULT || ae > AUDIO_ENCODER_AMR_NB) {
212        jniThrowException(env, "java/lang/IllegalArgumentException", "Invalid audio encoder");
213        return;
214    }
215    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
216    process_media_recorder_call(env, mr->setAudioEncoder(ae), "java/lang/RuntimeException", "setAudioEncoder failed.");
217}
218
219static void
220android_media_MediaRecorder_setOutputFileFD(JNIEnv *env, jobject thiz, jobject fileDescriptor, jlong offset, jlong length)
221{
222    LOGV("setOutputFile");
223    if (fileDescriptor == NULL) {
224        jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
225        return;
226    }
227    int fd = getParcelFileDescriptorFD(env, fileDescriptor);
228    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
229    status_t opStatus = mr->setOutputFile(fd, offset, length);
230    process_media_recorder_call(env, opStatus, "java/io/IOException", "setOutputFile failed.");
231}
232
233static void
234android_media_MediaRecorder_setVideoSize(JNIEnv *env, jobject thiz, jint width, jint height)
235{
236    LOGV("setVideoSize(%d, %d)", width, height);
237    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
238
239    if (width <= 0 || height <= 0) {
240        jniThrowException(env, "java/lang/IllegalArgumentException", "invalid video size");
241        return;
242    }
243    process_media_recorder_call(env, mr->setVideoSize(width, height), "java/lang/RuntimeException", "setVideoSize failed.");
244}
245
246static void
247android_media_MediaRecorder_setVideoFrameRate(JNIEnv *env, jobject thiz, jint rate)
248{
249    LOGV("setVideoFrameRate(%d)", rate);
250    if (rate <= 0 || rate > MEDIA_RECORDER_MAX_FRAME_RATE) {
251        jniThrowException(env, "java/lang/IllegalArgumentException", "invalid frame rate");
252        return;
253    }
254    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
255    process_media_recorder_call(env, mr->setVideoFrameRate(rate), "java/lang/RuntimeException", "setVideoFrameRate failed.");
256}
257
258static void
259android_media_MediaRecorder_prepare(JNIEnv *env, jobject thiz)
260{
261    LOGV("prepare");
262    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
263
264    jobject surface = env->GetObjectField(thiz, fields.surface);
265    if (surface != NULL) {
266        const sp<Surface>& native_surface = get_surface(env, surface);
267        LOGI("prepare: surface=%p (id=%d)", native_surface.get(), native_surface->ID());
268        if (process_media_recorder_call(env, mr->setPreviewSurface(native_surface), "java/lang/RuntimeException", "setPreviewSurface failed.")) {
269            return;
270        }
271    }
272    process_media_recorder_call(env, mr->prepare(), "java/io/IOException", "prepare failed.");
273}
274
275static int
276android_media_MediaRecorder_native_getMaxAmplitude(JNIEnv *env, jobject thiz)
277{
278    LOGV("getMaxAmplitude");
279    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
280    int result = 0;
281    process_media_recorder_call(env, mr->getMaxAmplitude(&result), "java/lang/RuntimeException", "getMaxAmplitude failed.");
282    return result;
283}
284
285static void
286android_media_MediaRecorder_start(JNIEnv *env, jobject thiz)
287{
288    LOGV("start");
289    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
290    process_media_recorder_call(env, mr->start(), "java/lang/RuntimeException", "start failed.");
291}
292
293static void
294android_media_MediaRecorder_stop(JNIEnv *env, jobject thiz)
295{
296    LOGV("stop");
297    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
298    process_media_recorder_call(env, mr->stop(), "java/lang/RuntimeException", "stop failed.");
299}
300
301static void
302android_media_MediaRecorder_native_reset(JNIEnv *env, jobject thiz)
303{
304    LOGV("native_reset");
305    sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
306    process_media_recorder_call(env, mr->reset(), "java/lang/RuntimeException", "native_reset failed.");
307}
308
309static void
310android_media_MediaRecorder_release(JNIEnv *env, jobject thiz)
311{
312    LOGV("release");
313    sp<MediaRecorder> mr = setMediaRecorder(env, thiz, 0);
314    if (mr != NULL) {
315        mr->setListener(NULL);
316    }
317}
318
319static void
320android_media_MediaRecorder_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
321{
322    LOGV("setup");
323    sp<MediaRecorder> mr = new MediaRecorder();
324    if (mr == NULL) {
325        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
326        return;
327    }
328    if (mr->initCheck() != NO_ERROR) {
329        jniThrowException(env, "java/lang/IOException", "Unable to initialize camera");
330        return;
331    }
332
333    // create new listener and give it to MediaRecorder
334    sp<JNIMediaRecorderListener> listener = new JNIMediaRecorderListener(env, thiz, weak_this);
335    mr->setListener(listener);
336
337    setMediaRecorder(env, thiz, mr);
338}
339
340static void
341android_media_MediaRecorder_native_finalize(JNIEnv *env, jobject thiz)
342{
343    LOGV("finalize");
344    android_media_MediaRecorder_release(env, thiz);
345}
346
347// ----------------------------------------------------------------------------
348
349static JNINativeMethod gMethods[] = {
350    {"setCamera",            "(Landroid/hardware/Camera;)V",    (void *)android_media_MediaRecorder_setCamera},
351    {"setVideoSource",       "(I)V",                            (void *)android_media_MediaRecorder_setVideoSource},
352    {"setAudioSource",       "(I)V",                            (void *)android_media_MediaRecorder_setAudioSource},
353    {"setOutputFormat",      "(I)V",                            (void *)android_media_MediaRecorder_setOutputFormat},
354    {"setVideoEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setVideoEncoder},
355    {"setAudioEncoder",      "(I)V",                            (void *)android_media_MediaRecorder_setAudioEncoder},
356    {"_setOutputFile",       "(Ljava/io/FileDescriptor;JJ)V",   (void *)android_media_MediaRecorder_setOutputFileFD},
357    {"setVideoSize",         "(II)V",                           (void *)android_media_MediaRecorder_setVideoSize},
358    {"setVideoFrameRate",    "(I)V",                            (void *)android_media_MediaRecorder_setVideoFrameRate},
359    {"_prepare",             "()V",                             (void *)android_media_MediaRecorder_prepare},
360    {"getMaxAmplitude",      "()I",                             (void *)android_media_MediaRecorder_native_getMaxAmplitude},
361    {"start",                "()V",                             (void *)android_media_MediaRecorder_start},
362    {"stop",                 "()V",                             (void *)android_media_MediaRecorder_stop},
363    {"native_reset",                "()V",                             (void *)android_media_MediaRecorder_native_reset},
364    {"release",              "()V",                             (void *)android_media_MediaRecorder_release},
365    {"native_setup",         "(Ljava/lang/Object;)V",           (void *)android_media_MediaRecorder_native_setup},
366    {"native_finalize",      "()V",                             (void *)android_media_MediaRecorder_native_finalize},
367};
368
369static const char* const kClassPathName = "android/media/MediaRecorder";
370
371int register_android_media_MediaRecorder(JNIEnv *env)
372{
373    jclass clazz;
374
375    clazz = env->FindClass("android/media/MediaRecorder");
376    if (clazz == NULL) {
377        LOGE("Can't find android/media/MediaRecorder");
378        return -1;
379    }
380
381    fields.context = env->GetFieldID(clazz, "mNativeContext", "I");
382    if (fields.context == NULL) {
383        LOGE("Can't find MediaRecorder.mNativeContext");
384        return -1;
385    }
386
387    fields.surface = env->GetFieldID(clazz, "mSurface", "Landroid/view/Surface;");
388    if (fields.surface == NULL) {
389        LOGE("Can't find MediaRecorder.mSurface");
390        return -1;
391    }
392
393    jclass surface = env->FindClass("android/view/Surface");
394    if (surface == NULL) {
395        LOGE("Can't find android/view/Surface");
396        return -1;
397    }
398
399    fields.surface_native = env->GetFieldID(surface, "mSurface", "I");
400    if (fields.surface_native == NULL) {
401        LOGE("Can't find Surface fields");
402        return -1;
403    }
404
405    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
406                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
407    if (fields.post_event == NULL) {
408        LOGE("Can't find MediaRecorder.postEventFromNative");
409        return -1;
410    }
411
412    return AndroidRuntime::registerNativeMethods(env,
413                "android/media/MediaRecorder", gMethods, NELEM(gMethods));
414}
415
416
417