MediaRecorder.java revision 00a009204e51997249d60eab4f147eff566e2b1f
1/*
2 * Copyright (C) 2007 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
17package android.media;
18
19import android.annotation.SystemApi;
20import android.app.ActivityThread;
21import android.hardware.Camera;
22import android.os.Handler;
23import android.os.Looper;
24import android.os.Message;
25import android.util.Log;
26import android.view.Surface;
27
28import java.io.FileDescriptor;
29import java.io.IOException;
30import java.io.RandomAccessFile;
31import java.lang.ref.WeakReference;
32
33/**
34 * Used to record audio and video. The recording control is based on a
35 * simple state machine (see below).
36 *
37 * <p><img src="{@docRoot}images/mediarecorder_state_diagram.gif" border="0" />
38 * </p>
39 *
40 * <p>A common case of using MediaRecorder to record audio works as follows:
41 *
42 * <pre>MediaRecorder recorder = new MediaRecorder();
43 * recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
44 * recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
45 * recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
46 * recorder.setOutputFile(PATH_NAME);
47 * recorder.prepare();
48 * recorder.start();   // Recording is now started
49 * ...
50 * recorder.stop();
51 * recorder.reset();   // You can reuse the object by going back to setAudioSource() step
52 * recorder.release(); // Now the object cannot be reused
53 * </pre>
54 *
55 * <p>Applications may want to register for informational and error
56 * events in order to be informed of some internal update and possible
57 * runtime errors during recording. Registration for such events is
58 * done by setting the appropriate listeners (via calls
59 * (to {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener and/or
60 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener).
61 * In order to receive the respective callback associated with these listeners,
62 * applications are required to create MediaRecorder objects on threads with a
63 * Looper running (the main UI thread by default already has a Looper running).
64 *
65 * <p><strong>Note:</strong> Currently, MediaRecorder does not work on the emulator.
66 *
67 * <div class="special reference">
68 * <h3>Developer Guides</h3>
69 * <p>For more information about how to use MediaRecorder for recording video, read the
70 * <a href="{@docRoot}guide/topics/media/camera.html#capture-video">Camera</a> developer guide.
71 * For more information about how to use MediaRecorder for recording sound, read the
72 * <a href="{@docRoot}guide/topics/media/audio-capture.html">Audio Capture</a> developer guide.</p>
73 * </div>
74 */
75public class MediaRecorder
76{
77    static {
78        System.loadLibrary("media_jni");
79        native_init();
80    }
81    private final static String TAG = "MediaRecorder";
82
83    // The two fields below are accessed by native methods
84    @SuppressWarnings("unused")
85    private long mNativeContext;
86
87    @SuppressWarnings("unused")
88    private Surface mSurface;
89
90    private String mPath;
91    private FileDescriptor mFd;
92    private EventHandler mEventHandler;
93    private OnErrorListener mOnErrorListener;
94    private OnInfoListener mOnInfoListener;
95
96    /**
97     * Default constructor.
98     */
99    public MediaRecorder() {
100
101        Looper looper;
102        if ((looper = Looper.myLooper()) != null) {
103            mEventHandler = new EventHandler(this, looper);
104        } else if ((looper = Looper.getMainLooper()) != null) {
105            mEventHandler = new EventHandler(this, looper);
106        } else {
107            mEventHandler = null;
108        }
109
110        String packageName = ActivityThread.currentPackageName();
111        /* Native setup requires a weak reference to our object.
112         * It's easier to create it here than in C++.
113         */
114        native_setup(new WeakReference<MediaRecorder>(this), packageName);
115    }
116
117    /**
118     * Sets a {@link android.hardware.Camera} to use for recording.
119     *
120     * <p>Use this function to switch quickly between preview and capture mode without a teardown of
121     * the camera object. {@link android.hardware.Camera#unlock()} should be called before
122     * this. Must call before {@link #prepare}.</p>
123     *
124     * @param c the Camera to use for recording
125     * @deprecated Use {@link #getSurface} and the {@link android.hardware.camera2} API instead.
126     */
127    @Deprecated
128    public native void setCamera(Camera c);
129
130    /**
131     * Gets the surface to record from when using SURFACE video source.
132     *
133     * <p> May only be called after {@link #prepare}. Frames rendered to the Surface before
134     * {@link #start} will be discarded.</p>
135     *
136     * @throws IllegalStateException if it is called before {@link #prepare}, after
137     * {@link #stop}, or is called when VideoSource is not set to SURFACE.
138     * @see android.media.MediaRecorder.VideoSource
139     */
140    public native Surface getSurface();
141
142    /**
143     * Sets a Surface to show a preview of recorded media (video). Calls this
144     * before prepare() to make sure that the desirable preview display is
145     * set. If {@link #setCamera(Camera)} is used and the surface has been
146     * already set to the camera, application do not need to call this. If
147     * this is called with non-null surface, the preview surface of the camera
148     * will be replaced by the new surface. If this method is called with null
149     * surface or not called at all, media recorder will not change the preview
150     * surface of the camera.
151     *
152     * @param sv the Surface to use for the preview
153     * @see android.hardware.Camera#setPreviewDisplay(android.view.SurfaceHolder)
154     */
155    public void setPreviewDisplay(Surface sv) {
156        mSurface = sv;
157    }
158
159    /**
160     * Defines the audio source. These constants are used with
161     * {@link MediaRecorder#setAudioSource(int)}.
162     */
163    public final class AudioSource {
164
165        private AudioSource() {}
166
167        /** @hide */
168        public final static int AUDIO_SOURCE_INVALID = -1;
169
170      /* Do not change these values without updating their counterparts
171       * in system/core/include/system/audio.h!
172       */
173
174        /** Default audio source **/
175        public static final int DEFAULT = 0;
176
177        /** Microphone audio source */
178        public static final int MIC = 1;
179
180        /** Voice call uplink (Tx) audio source */
181        public static final int VOICE_UPLINK = 2;
182
183        /** Voice call downlink (Rx) audio source */
184        public static final int VOICE_DOWNLINK = 3;
185
186        /** Voice call uplink + downlink audio source */
187        public static final int VOICE_CALL = 4;
188
189        /** Microphone audio source with same orientation as camera if available, the main
190         *  device microphone otherwise */
191        public static final int CAMCORDER = 5;
192
193        /** Microphone audio source tuned for voice recognition if available, behaves like
194         *  {@link #DEFAULT} otherwise. */
195        public static final int VOICE_RECOGNITION = 6;
196
197        /** Microphone audio source tuned for voice communications such as VoIP. It
198         *  will for instance take advantage of echo cancellation or automatic gain control
199         *  if available. It otherwise behaves like {@link #DEFAULT} if no voice processing
200         *  is applied.
201         */
202        public static final int VOICE_COMMUNICATION = 7;
203
204        /**
205         * Audio source for a submix of audio streams to be presented remotely.
206         * <p>
207         * An application can use this audio source to capture a mix of audio streams
208         * that should be transmitted to a remote receiver such as a Wifi display.
209         * While recording is active, these audio streams are redirected to the remote
210         * submix instead of being played on the device speaker or headset.
211         * </p><p>
212         * Certain streams are excluded from the remote submix, including
213         * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_ALARM},
214         * and {@link AudioManager#STREAM_NOTIFICATION}.  These streams will continue
215         * to be presented locally as usual.
216         * </p><p>
217         * Capturing the remote submix audio requires the
218         * {@link android.Manifest.permission#CAPTURE_AUDIO_OUTPUT} permission.
219         * This permission is reserved for use by system components and is not available to
220         * third-party applications.
221         * </p>
222         */
223        public static final int REMOTE_SUBMIX = 8;
224
225        /**
226         * Audio source for capturing broadcast radio tuner output.
227         * @hide
228         */
229        @SystemApi
230        public static final int RADIO_TUNER = 1998;
231
232        /**
233         * Audio source for preemptible, low-priority software hotword detection
234         * It presents the same gain and pre processing tuning as {@link #VOICE_RECOGNITION}.
235         * <p>
236         * An application should use this audio source when it wishes to do
237         * always-on software hotword detection, while gracefully giving in to any other application
238         * that might want to read from the microphone.
239         * </p>
240         * This is a hidden audio source.
241         * @hide
242         */
243        @SystemApi
244        public static final int HOTWORD = 1999;
245    }
246
247    /**
248     * Defines the video source. These constants are used with
249     * {@link MediaRecorder#setVideoSource(int)}.
250     */
251    public final class VideoSource {
252      /* Do not change these values without updating their counterparts
253       * in include/media/mediarecorder.h!
254       */
255        private VideoSource() {}
256        public static final int DEFAULT = 0;
257        /** Camera video source
258         * <p>
259         * Using the {@link android.hardware.Camera} API as video source.
260         * </p>
261         */
262        public static final int CAMERA = 1;
263        /** Surface video source
264         * <p>
265         * Using a Surface as video source.
266         * </p><p>
267         * This flag must be used when recording from an
268         * {@link android.hardware.camera2} API source.
269         * </p><p>
270         * When using this video source type, use {@link MediaRecorder#getSurface()}
271         * to retrieve the surface created by MediaRecorder.
272         */
273        public static final int SURFACE = 2;
274    }
275
276    /**
277     * Defines the output format. These constants are used with
278     * {@link MediaRecorder#setOutputFormat(int)}.
279     */
280    public final class OutputFormat {
281      /* Do not change these values without updating their counterparts
282       * in include/media/mediarecorder.h!
283       */
284        private OutputFormat() {}
285        public static final int DEFAULT = 0;
286        /** 3GPP media file format*/
287        public static final int THREE_GPP = 1;
288        /** MPEG4 media file format*/
289        public static final int MPEG_4 = 2;
290
291        /** The following formats are audio only .aac or .amr formats */
292
293        /**
294         * AMR NB file format
295         * @deprecated  Deprecated in favor of MediaRecorder.OutputFormat.AMR_NB
296         */
297        public static final int RAW_AMR = 3;
298
299        /** AMR NB file format */
300        public static final int AMR_NB = 3;
301
302        /** AMR WB file format */
303        public static final int AMR_WB = 4;
304
305        /** @hide AAC ADIF file format */
306        public static final int AAC_ADIF = 5;
307
308        /** AAC ADTS file format */
309        public static final int AAC_ADTS = 6;
310
311        /** @hide Stream over a socket, limited to a single stream */
312        public static final int OUTPUT_FORMAT_RTP_AVP = 7;
313
314        /** @hide H.264/AAC data encapsulated in MPEG2/TS */
315        public static final int OUTPUT_FORMAT_MPEG2TS = 8;
316
317        /** VP8/VORBIS data in a WEBM container */
318        public static final int WEBM = 9;
319    };
320
321    /**
322     * Defines the audio encoding. These constants are used with
323     * {@link MediaRecorder#setAudioEncoder(int)}.
324     */
325    public final class AudioEncoder {
326      /* Do not change these values without updating their counterparts
327       * in include/media/mediarecorder.h!
328       */
329        private AudioEncoder() {}
330        public static final int DEFAULT = 0;
331        /** AMR (Narrowband) audio codec */
332        public static final int AMR_NB = 1;
333        /** AMR (Wideband) audio codec */
334        public static final int AMR_WB = 2;
335        /** AAC Low Complexity (AAC-LC) audio codec */
336        public static final int AAC = 3;
337        /** High Efficiency AAC (HE-AAC) audio codec */
338        public static final int HE_AAC = 4;
339        /** Enhanced Low Delay AAC (AAC-ELD) audio codec */
340        public static final int AAC_ELD = 5;
341        /** Ogg Vorbis audio codec */
342        public static final int VORBIS = 6;
343    }
344
345    /**
346     * Defines the video encoding. These constants are used with
347     * {@link MediaRecorder#setVideoEncoder(int)}.
348     */
349    public final class VideoEncoder {
350      /* Do not change these values without updating their counterparts
351       * in include/media/mediarecorder.h!
352       */
353        private VideoEncoder() {}
354        public static final int DEFAULT = 0;
355        public static final int H263 = 1;
356        public static final int H264 = 2;
357        public static final int MPEG_4_SP = 3;
358        public static final int VP8 = 4;
359    }
360
361    /**
362     * Sets the audio source to be used for recording. If this method is not
363     * called, the output file will not contain an audio track. The source needs
364     * to be specified before setting recording-parameters or encoders. Call
365     * this only before setOutputFormat().
366     *
367     * @param audio_source the audio source to use
368     * @throws IllegalStateException if it is called after setOutputFormat()
369     * @see android.media.MediaRecorder.AudioSource
370     */
371    public native void setAudioSource(int audio_source)
372            throws IllegalStateException;
373
374    /**
375     * Gets the maximum value for audio sources.
376     * @see android.media.MediaRecorder.AudioSource
377     */
378    public static final int getAudioSourceMax() {
379        return AudioSource.REMOTE_SUBMIX;
380    }
381
382    /**
383     * Sets the video source to be used for recording. If this method is not
384     * called, the output file will not contain an video track. The source needs
385     * to be specified before setting recording-parameters or encoders. Call
386     * this only before setOutputFormat().
387     *
388     * @param video_source the video source to use
389     * @throws IllegalStateException if it is called after setOutputFormat()
390     * @see android.media.MediaRecorder.VideoSource
391     */
392    public native void setVideoSource(int video_source)
393            throws IllegalStateException;
394
395    /**
396     * Uses the settings from a CamcorderProfile object for recording. This method should
397     * be called after the video AND audio sources are set, and before setOutputFile().
398     * If a time lapse CamcorderProfile is used, audio related source or recording
399     * parameters are ignored.
400     *
401     * @param profile the CamcorderProfile to use
402     * @see android.media.CamcorderProfile
403     */
404    public void setProfile(CamcorderProfile profile) {
405        setOutputFormat(profile.fileFormat);
406        setVideoFrameRate(profile.videoFrameRate);
407        setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
408        setVideoEncodingBitRate(profile.videoBitRate);
409        setVideoEncoder(profile.videoCodec);
410        if (profile.quality >= CamcorderProfile.QUALITY_TIME_LAPSE_LOW &&
411             profile.quality <= CamcorderProfile.QUALITY_TIME_LAPSE_QVGA) {
412            // Nothing needs to be done. Call to setCaptureRate() enables
413            // time lapse video recording.
414        } else {
415            setAudioEncodingBitRate(profile.audioBitRate);
416            setAudioChannels(profile.audioChannels);
417            setAudioSamplingRate(profile.audioSampleRate);
418            setAudioEncoder(profile.audioCodec);
419        }
420    }
421
422    /**
423     * Set video frame capture rate. This can be used to set a different video frame capture
424     * rate than the recorded video's playback rate. This method also sets the recording mode
425     * to time lapse. In time lapse video recording, only video is recorded. Audio related
426     * parameters are ignored when a time lapse recording session starts, if an application
427     * sets them.
428     *
429     * @param fps Rate at which frames should be captured in frames per second.
430     * The fps can go as low as desired. However the fastest fps will be limited by the hardware.
431     * For resolutions that can be captured by the video camera, the fastest fps can be computed using
432     * {@link android.hardware.Camera.Parameters#getPreviewFpsRange(int[])}. For higher
433     * resolutions the fastest fps may be more restrictive.
434     * Note that the recorder cannot guarantee that frames will be captured at the
435     * given rate due to camera/encoder limitations. However it tries to be as close as
436     * possible.
437     */
438    public void setCaptureRate(double fps) {
439        // Make sure that time lapse is enabled when this method is called.
440        setParameter("time-lapse-enable=1");
441        setParameter("time-lapse-fps=" + fps);
442    }
443
444    /**
445     * Sets the orientation hint for output video playback.
446     * This method should be called before prepare(). This method will not
447     * trigger the source video frame to rotate during video recording, but to
448     * add a composition matrix containing the rotation angle in the output
449     * video if the output format is OutputFormat.THREE_GPP or
450     * OutputFormat.MPEG_4 so that a video player can choose the proper
451     * orientation for playback. Note that some video players may choose
452     * to ignore the compostion matrix in a video during playback.
453     *
454     * @param degrees the angle to be rotated clockwise in degrees.
455     * The supported angles are 0, 90, 180, and 270 degrees.
456     * @throws IllegalArgumentException if the angle is not supported.
457     *
458     */
459    public void setOrientationHint(int degrees) {
460        if (degrees != 0   &&
461            degrees != 90  &&
462            degrees != 180 &&
463            degrees != 270) {
464            throw new IllegalArgumentException("Unsupported angle: " + degrees);
465        }
466        setParameter("video-param-rotation-angle-degrees=" + degrees);
467    }
468
469    /**
470     * Set and store the geodata (latitude and longitude) in the output file.
471     * This method should be called before prepare(). The geodata is
472     * stored in udta box if the output format is OutputFormat.THREE_GPP
473     * or OutputFormat.MPEG_4, and is ignored for other output formats.
474     * The geodata is stored according to ISO-6709 standard.
475     *
476     * @param latitude latitude in degrees. Its value must be in the
477     * range [-90, 90].
478     * @param longitude longitude in degrees. Its value must be in the
479     * range [-180, 180].
480     *
481     * @throws IllegalArgumentException if the given latitude or
482     * longitude is out of range.
483     *
484     */
485    public void setLocation(float latitude, float longitude) {
486        int latitudex10000  = (int) (latitude * 10000 + 0.5);
487        int longitudex10000 = (int) (longitude * 10000 + 0.5);
488
489        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
490            String msg = "Latitude: " + latitude + " out of range.";
491            throw new IllegalArgumentException(msg);
492        }
493        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
494            String msg = "Longitude: " + longitude + " out of range";
495            throw new IllegalArgumentException(msg);
496        }
497
498        setParameter("param-geotag-latitude=" + latitudex10000);
499        setParameter("param-geotag-longitude=" + longitudex10000);
500    }
501
502    /**
503     * Sets the format of the output file produced during recording. Call this
504     * after setAudioSource()/setVideoSource() but before prepare().
505     *
506     * <p>It is recommended to always use 3GP format when using the H.263
507     * video encoder and AMR audio encoder. Using an MPEG-4 container format
508     * may confuse some desktop players.</p>
509     *
510     * @param output_format the output format to use. The output format
511     * needs to be specified before setting recording-parameters or encoders.
512     * @throws IllegalStateException if it is called after prepare() or before
513     * setAudioSource()/setVideoSource().
514     * @see android.media.MediaRecorder.OutputFormat
515     */
516    public native void setOutputFormat(int output_format)
517            throws IllegalStateException;
518
519    /**
520     * Sets the width and height of the video to be captured.  Must be called
521     * after setVideoSource(). Call this after setOutFormat() but before
522     * prepare().
523     *
524     * @param width the width of the video to be captured
525     * @param height the height of the video to be captured
526     * @throws IllegalStateException if it is called after
527     * prepare() or before setOutputFormat()
528     */
529    public native void setVideoSize(int width, int height)
530            throws IllegalStateException;
531
532    /**
533     * Sets the frame rate of the video to be captured.  Must be called
534     * after setVideoSource(). Call this after setOutFormat() but before
535     * prepare().
536     *
537     * @param rate the number of frames per second of video to capture
538     * @throws IllegalStateException if it is called after
539     * prepare() or before setOutputFormat().
540     *
541     * NOTE: On some devices that have auto-frame rate, this sets the
542     * maximum frame rate, not a constant frame rate. Actual frame rate
543     * will vary according to lighting conditions.
544     */
545    public native void setVideoFrameRate(int rate) throws IllegalStateException;
546
547    /**
548     * Sets the maximum duration (in ms) of the recording session.
549     * Call this after setOutFormat() but before prepare().
550     * After recording reaches the specified duration, a notification
551     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
552     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
553     * and recording will be stopped. Stopping happens asynchronously, there
554     * is no guarantee that the recorder will have stopped by the time the
555     * listener is notified.
556     *
557     * @param max_duration_ms the maximum duration in ms (if zero or negative, disables the duration limit)
558     *
559     */
560    public native void setMaxDuration(int max_duration_ms) throws IllegalArgumentException;
561
562    /**
563     * Sets the maximum filesize (in bytes) of the recording session.
564     * Call this after setOutFormat() but before prepare().
565     * After recording reaches the specified filesize, a notification
566     * will be sent to the {@link android.media.MediaRecorder.OnInfoListener}
567     * with a "what" code of {@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
568     * and recording will be stopped. Stopping happens asynchronously, there
569     * is no guarantee that the recorder will have stopped by the time the
570     * listener is notified.
571     *
572     * @param max_filesize_bytes the maximum filesize in bytes (if zero or negative, disables the limit)
573     *
574     */
575    public native void setMaxFileSize(long max_filesize_bytes) throws IllegalArgumentException;
576
577    /**
578     * Sets the audio encoder to be used for recording. If this method is not
579     * called, the output file will not contain an audio track. Call this after
580     * setOutputFormat() but before prepare().
581     *
582     * @param audio_encoder the audio encoder to use.
583     * @throws IllegalStateException if it is called before
584     * setOutputFormat() or after prepare().
585     * @see android.media.MediaRecorder.AudioEncoder
586     */
587    public native void setAudioEncoder(int audio_encoder)
588            throws IllegalStateException;
589
590    /**
591     * Sets the video encoder to be used for recording. If this method is not
592     * called, the output file will not contain an video track. Call this after
593     * setOutputFormat() and before prepare().
594     *
595     * @param video_encoder the video encoder to use.
596     * @throws IllegalStateException if it is called before
597     * setOutputFormat() or after prepare()
598     * @see android.media.MediaRecorder.VideoEncoder
599     */
600    public native void setVideoEncoder(int video_encoder)
601            throws IllegalStateException;
602
603    /**
604     * Sets the audio sampling rate for recording. Call this method before prepare().
605     * Prepare() may perform additional checks on the parameter to make sure whether
606     * the specified audio sampling rate is applicable. The sampling rate really depends
607     * on the format for the audio recording, as well as the capabilities of the platform.
608     * For instance, the sampling rate supported by AAC audio coding standard ranges
609     * from 8 to 96 kHz, the sampling rate supported by AMRNB is 8kHz, and the sampling
610     * rate supported by AMRWB is 16kHz. Please consult with the related audio coding
611     * standard for the supported audio sampling rate.
612     *
613     * @param samplingRate the sampling rate for audio in samples per second.
614     */
615    public void setAudioSamplingRate(int samplingRate) {
616        if (samplingRate <= 0) {
617            throw new IllegalArgumentException("Audio sampling rate is not positive");
618        }
619        setParameter("audio-param-sampling-rate=" + samplingRate);
620    }
621
622    /**
623     * Sets the number of audio channels for recording. Call this method before prepare().
624     * Prepare() may perform additional checks on the parameter to make sure whether the
625     * specified number of audio channels are applicable.
626     *
627     * @param numChannels the number of audio channels. Usually it is either 1 (mono) or 2
628     * (stereo).
629     */
630    public void setAudioChannels(int numChannels) {
631        if (numChannels <= 0) {
632            throw new IllegalArgumentException("Number of channels is not positive");
633        }
634        setParameter("audio-param-number-of-channels=" + numChannels);
635    }
636
637    /**
638     * Sets the audio encoding bit rate for recording. Call this method before prepare().
639     * Prepare() may perform additional checks on the parameter to make sure whether the
640     * specified bit rate is applicable, and sometimes the passed bitRate will be clipped
641     * internally to ensure the audio recording can proceed smoothly based on the
642     * capabilities of the platform.
643     *
644     * @param bitRate the audio encoding bit rate in bits per second.
645     */
646    public void setAudioEncodingBitRate(int bitRate) {
647        if (bitRate <= 0) {
648            throw new IllegalArgumentException("Audio encoding bit rate is not positive");
649        }
650        setParameter("audio-param-encoding-bitrate=" + bitRate);
651    }
652
653    /**
654     * Sets the video encoding bit rate for recording. Call this method before prepare().
655     * Prepare() may perform additional checks on the parameter to make sure whether the
656     * specified bit rate is applicable, and sometimes the passed bitRate will be
657     * clipped internally to ensure the video recording can proceed smoothly based on
658     * the capabilities of the platform.
659     *
660     * @param bitRate the video encoding bit rate in bits per second.
661     */
662    public void setVideoEncodingBitRate(int bitRate) {
663        if (bitRate <= 0) {
664            throw new IllegalArgumentException("Video encoding bit rate is not positive");
665        }
666        setParameter("video-param-encoding-bitrate=" + bitRate);
667    }
668
669    /**
670     * Currently not implemented. It does nothing.
671     * @deprecated Time lapse mode video recording using camera still image capture
672     * is not desirable, and will not be supported.
673     * @hide
674     */
675    public void setAuxiliaryOutputFile(FileDescriptor fd)
676    {
677        Log.w(TAG, "setAuxiliaryOutputFile(FileDescriptor) is no longer supported.");
678    }
679
680    /**
681     * Currently not implemented. It does nothing.
682     * @deprecated Time lapse mode video recording using camera still image capture
683     * is not desirable, and will not be supported.
684     * @hide
685     */
686    public void setAuxiliaryOutputFile(String path)
687    {
688        Log.w(TAG, "setAuxiliaryOutputFile(String) is no longer supported.");
689    }
690
691    /**
692     * Pass in the file descriptor of the file to be written. Call this after
693     * setOutputFormat() but before prepare().
694     *
695     * @param fd an open file descriptor to be written into.
696     * @throws IllegalStateException if it is called before
697     * setOutputFormat() or after prepare()
698     */
699    public void setOutputFile(FileDescriptor fd) throws IllegalStateException
700    {
701        mPath = null;
702        mFd = fd;
703    }
704
705    /**
706     * Sets the path of the output file to be produced. Call this after
707     * setOutputFormat() but before prepare().
708     *
709     * @param path The pathname to use.
710     * @throws IllegalStateException if it is called before
711     * setOutputFormat() or after prepare()
712     */
713    public void setOutputFile(String path) throws IllegalStateException
714    {
715        mFd = null;
716        mPath = path;
717    }
718
719    // native implementation
720    private native void _setOutputFile(FileDescriptor fd, long offset, long length)
721        throws IllegalStateException, IOException;
722    private native void _prepare() throws IllegalStateException, IOException;
723
724    /**
725     * Prepares the recorder to begin capturing and encoding data. This method
726     * must be called after setting up the desired audio and video sources,
727     * encoders, file format, etc., but before start().
728     *
729     * @throws IllegalStateException if it is called after
730     * start() or before setOutputFormat().
731     * @throws IOException if prepare fails otherwise.
732     */
733    public void prepare() throws IllegalStateException, IOException
734    {
735        if (mPath != null) {
736            RandomAccessFile file = new RandomAccessFile(mPath, "rws");
737            try {
738                _setOutputFile(file.getFD(), 0, 0);
739            } finally {
740                file.close();
741            }
742        } else if (mFd != null) {
743            _setOutputFile(mFd, 0, 0);
744        } else {
745            throw new IOException("No valid output file");
746        }
747
748        _prepare();
749    }
750
751    /**
752     * Begins capturing and encoding data to the file specified with
753     * setOutputFile(). Call this after prepare().
754     *
755     * <p>Since API level 13, if applications set a camera via
756     * {@link #setCamera(Camera)}, the apps can use the camera after this method
757     * call. The apps do not need to lock the camera again. However, if this
758     * method fails, the apps should still lock the camera back. The apps should
759     * not start another recording session during recording.
760     *
761     * @throws IllegalStateException if it is called before
762     * prepare().
763     */
764    public native void start() throws IllegalStateException;
765
766    /**
767     * Stops recording. Call this after start(). Once recording is stopped,
768     * you will have to configure it again as if it has just been constructed.
769     * Note that a RuntimeException is intentionally thrown to the
770     * application, if no valid audio/video data has been received when stop()
771     * is called. This happens if stop() is called immediately after
772     * start(). The failure lets the application take action accordingly to
773     * clean up the output file (delete the output file, for instance), since
774     * the output file is not properly constructed when this happens.
775     *
776     * @throws IllegalStateException if it is called before start()
777     */
778    public native void stop() throws IllegalStateException;
779
780    /**
781     * Restarts the MediaRecorder to its idle state. After calling
782     * this method, you will have to configure it again as if it had just been
783     * constructed.
784     */
785    public void reset() {
786        native_reset();
787
788        // make sure none of the listeners get called anymore
789        mEventHandler.removeCallbacksAndMessages(null);
790    }
791
792    private native void native_reset();
793
794    /**
795     * Returns the maximum absolute amplitude that was sampled since the last
796     * call to this method. Call this only after the setAudioSource().
797     *
798     * @return the maximum absolute amplitude measured since the last call, or
799     * 0 when called for the first time
800     * @throws IllegalStateException if it is called before
801     * the audio source has been set.
802     */
803    public native int getMaxAmplitude() throws IllegalStateException;
804
805    /* Do not change this value without updating its counterpart
806     * in include/media/mediarecorder.h or mediaplayer.h!
807     */
808    /** Unspecified media recorder error.
809     * @see android.media.MediaRecorder.OnErrorListener
810     */
811    public static final int MEDIA_RECORDER_ERROR_UNKNOWN = 1;
812    /** Media server died. In this case, the application must release the
813     * MediaRecorder object and instantiate a new one.
814     * @see android.media.MediaRecorder.OnErrorListener
815     */
816    public static final int MEDIA_ERROR_SERVER_DIED = 100;
817
818    /**
819     * Interface definition for a callback to be invoked when an error
820     * occurs while recording.
821     */
822    public interface OnErrorListener
823    {
824        /**
825         * Called when an error occurs while recording.
826         *
827         * @param mr the MediaRecorder that encountered the error
828         * @param what    the type of error that has occurred:
829         * <ul>
830         * <li>{@link #MEDIA_RECORDER_ERROR_UNKNOWN}
831         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
832         * </ul>
833         * @param extra   an extra code, specific to the error type
834         */
835        void onError(MediaRecorder mr, int what, int extra);
836    }
837
838    /**
839     * Register a callback to be invoked when an error occurs while
840     * recording.
841     *
842     * @param l the callback that will be run
843     */
844    public void setOnErrorListener(OnErrorListener l)
845    {
846        mOnErrorListener = l;
847    }
848
849    /* Do not change these values without updating their counterparts
850     * in include/media/mediarecorder.h!
851     */
852    /** Unspecified media recorder error.
853     * @see android.media.MediaRecorder.OnInfoListener
854     */
855    public static final int MEDIA_RECORDER_INFO_UNKNOWN              = 1;
856    /** A maximum duration had been setup and has now been reached.
857     * @see android.media.MediaRecorder.OnInfoListener
858     */
859    public static final int MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800;
860    /** A maximum filesize had been setup and has now been reached.
861     * @see android.media.MediaRecorder.OnInfoListener
862     */
863    public static final int MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801;
864
865    /** informational events for individual tracks, for testing purpose.
866     * The track informational event usually contains two parts in the ext1
867     * arg of the onInfo() callback: bit 31-28 contains the track id; and
868     * the rest of the 28 bits contains the informational event defined here.
869     * For example, ext1 = (1 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the
870     * track id is 1 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE;
871     * while ext1 = (0 << 28 | MEDIA_RECORDER_TRACK_INFO_TYPE) if the track
872     * id is 0 for informational event MEDIA_RECORDER_TRACK_INFO_TYPE. The
873     * application should extract the track id and the type of informational
874     * event from ext1, accordingly.
875     *
876     * FIXME:
877     * Please update the comment for onInfo also when these
878     * events are unhidden so that application knows how to extract the track
879     * id and the informational event type from onInfo callback.
880     *
881     * {@hide}
882     */
883    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_START        = 1000;
884    /** Signal the completion of the track for the recording session.
885     * {@hide}
886     */
887    public static final int MEDIA_RECORDER_TRACK_INFO_COMPLETION_STATUS = 1000;
888    /** Indicate the recording progress in time (ms) during recording.
889     * {@hide}
890     */
891    public static final int MEDIA_RECORDER_TRACK_INFO_PROGRESS_IN_TIME  = 1001;
892    /** Indicate the track type: 0 for Audio and 1 for Video.
893     * {@hide}
894     */
895    public static final int MEDIA_RECORDER_TRACK_INFO_TYPE              = 1002;
896    /** Provide the track duration information.
897     * {@hide}
898     */
899    public static final int MEDIA_RECORDER_TRACK_INFO_DURATION_MS       = 1003;
900    /** Provide the max chunk duration in time (ms) for the given track.
901     * {@hide}
902     */
903    public static final int MEDIA_RECORDER_TRACK_INFO_MAX_CHUNK_DUR_MS  = 1004;
904    /** Provide the total number of recordd frames.
905     * {@hide}
906     */
907    public static final int MEDIA_RECORDER_TRACK_INFO_ENCODED_FRAMES    = 1005;
908    /** Provide the max spacing between neighboring chunks for the given track.
909     * {@hide}
910     */
911    public static final int MEDIA_RECORDER_TRACK_INTER_CHUNK_TIME_MS    = 1006;
912    /** Provide the elapsed time measuring from the start of the recording
913     * till the first output frame of the given track is received, excluding
914     * any intentional start time offset of a recording session for the
915     * purpose of eliminating the recording sound in the recorded file.
916     * {@hide}
917     */
918    public static final int MEDIA_RECORDER_TRACK_INFO_INITIAL_DELAY_MS  = 1007;
919    /** Provide the start time difference (delay) betweeen this track and
920     * the start of the movie.
921     * {@hide}
922     */
923    public static final int MEDIA_RECORDER_TRACK_INFO_START_OFFSET_MS   = 1008;
924    /** Provide the total number of data (in kilo-bytes) encoded.
925     * {@hide}
926     */
927    public static final int MEDIA_RECORDER_TRACK_INFO_DATA_KBYTES       = 1009;
928    /**
929     * {@hide}
930     */
931    public static final int MEDIA_RECORDER_TRACK_INFO_LIST_END          = 2000;
932
933
934    /**
935     * Interface definition for a callback to be invoked when an error
936     * occurs while recording.
937     */
938    public interface OnInfoListener
939    {
940        /**
941         * Called when an error occurs while recording.
942         *
943         * @param mr the MediaRecorder that encountered the error
944         * @param what    the type of error that has occurred:
945         * <ul>
946         * <li>{@link #MEDIA_RECORDER_INFO_UNKNOWN}
947         * <li>{@link #MEDIA_RECORDER_INFO_MAX_DURATION_REACHED}
948         * <li>{@link #MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED}
949         * </ul>
950         * @param extra   an extra code, specific to the error type
951         */
952        void onInfo(MediaRecorder mr, int what, int extra);
953    }
954
955    /**
956     * Register a callback to be invoked when an informational event occurs while
957     * recording.
958     *
959     * @param listener the callback that will be run
960     */
961    public void setOnInfoListener(OnInfoListener listener)
962    {
963        mOnInfoListener = listener;
964    }
965
966    private class EventHandler extends Handler
967    {
968        private MediaRecorder mMediaRecorder;
969
970        public EventHandler(MediaRecorder mr, Looper looper) {
971            super(looper);
972            mMediaRecorder = mr;
973        }
974
975        /* Do not change these values without updating their counterparts
976         * in include/media/mediarecorder.h!
977         */
978        private static final int MEDIA_RECORDER_EVENT_LIST_START = 1;
979        private static final int MEDIA_RECORDER_EVENT_ERROR      = 1;
980        private static final int MEDIA_RECORDER_EVENT_INFO       = 2;
981        private static final int MEDIA_RECORDER_EVENT_LIST_END   = 99;
982
983        /* Events related to individual tracks */
984        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_START = 100;
985        private static final int MEDIA_RECORDER_TRACK_EVENT_ERROR      = 100;
986        private static final int MEDIA_RECORDER_TRACK_EVENT_INFO       = 101;
987        private static final int MEDIA_RECORDER_TRACK_EVENT_LIST_END   = 1000;
988
989
990        @Override
991        public void handleMessage(Message msg) {
992            if (mMediaRecorder.mNativeContext == 0) {
993                Log.w(TAG, "mediarecorder went away with unhandled events");
994                return;
995            }
996            switch(msg.what) {
997            case MEDIA_RECORDER_EVENT_ERROR:
998            case MEDIA_RECORDER_TRACK_EVENT_ERROR:
999                if (mOnErrorListener != null)
1000                    mOnErrorListener.onError(mMediaRecorder, msg.arg1, msg.arg2);
1001
1002                return;
1003
1004            case MEDIA_RECORDER_EVENT_INFO:
1005            case MEDIA_RECORDER_TRACK_EVENT_INFO:
1006                if (mOnInfoListener != null)
1007                    mOnInfoListener.onInfo(mMediaRecorder, msg.arg1, msg.arg2);
1008
1009                return;
1010
1011            default:
1012                Log.e(TAG, "Unknown message type " + msg.what);
1013                return;
1014            }
1015        }
1016    }
1017
1018    /**
1019     * Called from native code when an interesting event happens.  This method
1020     * just uses the EventHandler system to post the event back to the main app thread.
1021     * We use a weak reference to the original MediaRecorder object so that the native
1022     * code is safe from the object disappearing from underneath it.  (This is
1023     * the cookie passed to native_setup().)
1024     */
1025    private static void postEventFromNative(Object mediarecorder_ref,
1026                                            int what, int arg1, int arg2, Object obj)
1027    {
1028        MediaRecorder mr = (MediaRecorder)((WeakReference)mediarecorder_ref).get();
1029        if (mr == null) {
1030            return;
1031        }
1032
1033        if (mr.mEventHandler != null) {
1034            Message m = mr.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1035            mr.mEventHandler.sendMessage(m);
1036        }
1037    }
1038
1039    /**
1040     * Releases resources associated with this MediaRecorder object.
1041     * It is good practice to call this method when you're done
1042     * using the MediaRecorder. In particular, whenever an Activity
1043     * of an application is paused (its onPause() method is called),
1044     * or stopped (its onStop() method is called), this method should be
1045     * invoked to release the MediaRecorder object, unless the application
1046     * has a special need to keep the object around. In addition to
1047     * unnecessary resources (such as memory and instances of codecs)
1048     * being held, failure to call this method immediately if a
1049     * MediaRecorder object is no longer needed may also lead to
1050     * continuous battery consumption for mobile devices, and recording
1051     * failure for other applications if no multiple instances of the
1052     * same codec are supported on a device. Even if multiple instances
1053     * of the same codec are supported, some performance degradation
1054     * may be expected when unnecessary multiple instances are used
1055     * at the same time.
1056     */
1057    public native void release();
1058
1059    private static native final void native_init();
1060
1061    private native final void native_setup(Object mediarecorder_this,
1062            String clientName) throws IllegalStateException;
1063
1064    private native final void native_finalize();
1065
1066    private native void setParameter(String nameValuePair);
1067
1068    @Override
1069    protected void finalize() { native_finalize(); }
1070}
1071